SwiftUI oddity with optionals

found this oddity in SwiftUI. compiler bug?

import SwiftUI

var image: Image?

struct ContentView: View {
	var body: some View {
		image! // ok
		image!.resizable() // ok
		// image.resizable() // "image must be unwrapped" error (expected)
		image?.resizable() // no error?! (unexpected)
		image.frame(width: 0, height: 0) // no error?! (unexpected)
		image // no error?! (unexpected)
	}
}
1 Like

Optional conforms to View when its Wrapped type does.

3 Likes

It's vary useful to transform some Optional value to a view that display the value:

anOptional.map { SomeView($0) }

If anOptional is nil, it's as-if nothing there.

looks a "clever hack" to me. this reads cleaner:

        if let v = anOptional {
            SomeView(v)
        }

(can put on one line as well but wouldn't do this personally - as it would be harder to step through in the debugger and makes it less visually appealing.)

OTOH this also looks a clever hack for me from SwiftUI:

var body: some View {
    if let s = anOptional {
        Text(s)
    }
} // compiles fine

quite different to traditional swift whereas it leads to a "missing return in a function" error.

so in this particular case your version looks indeed "less odd" overall:

var body: some View {
    anOptional.map { v in
       SomeView(v)
    }
}
1 Like

I agree. The map version used to be required when result builders (née function builders) didn't support if let.

1 Like