by stormbrew · 10y ago · 0 comments
Which is why you can do exactly that.
if let checked = blah { /* checked does not need ! or ? */ }guard let foo = optFoo { Swift.print("oops, this optional thing wasn't optional") }
Swift.print("now \(foo) is in scope and non-nil")
will it be a runtime error? like a memory access violation in c++?
what's the benefit of adding !? if it generates the same access violation runtime error?
let foo = bar!
If bar is nil, you'll get a runtime error "unexpectedly found nil when unwrapping bar"
in my opinion, the benefit of optionals in general is that it allows you to guarantee at compile time that certain variables (non optionals) will _never_ be nil, which enables all kinds of compiler optimizations.
Edit to add: And unless something has changed since I last tried it, you can also just shadow blah so that inside that scope you're referring to the unwrapped one:
if let blah = blah { /* use blah here, it's unwrapped */ }
It looks kind of silly, but I have used it where there was no better name for the unwrapped value.I still don't understand the point of ! and ?
less is more, swift ought to know.
You seem to be insisting on using ! and then blaming the language for letting you shoot your foot off with it...