Search code examples
imageswiftuiextension-methods

SwiftUI: Extending the Image type to return an image processed through a method


This approach does not work for me and I can't figure out how to do it.


extension Image {
    func getResizedImage(_ imageName: String) -> any View {
        return Image(imageName)
            .resizable()
    }
}

// then ...

struct ContentView: View {
    var body: some View {
        Image.getResizedImage("myImageFromAssets")
    }
} ```

Solution

  • Two issues:

    1. Because you're calling this on Image, you need a static function

    2. The function should return some View, not any View

    extension Image {
        static func getResizedImage(_ imageName: String) -> some View {
            return Image(imageName)
                .resizable()
        }
    }
    
    struct ContentView: View {
        var body: some View {
            Image.getResizedImage("myImageFromAssets")
        }
    }