tera
1
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
Jon_Shier
(Jon Shier)
2
Optional conforms to View when its Wrapped type does.
3 Likes
young
(rtSwift)
3
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.
tera
4
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
Jon_Shier
(Jon Shier)
5
I agree. The map version used to be required when result builders (née function builders) didn't support if let.
1 Like