This one is really puzzling me: What's the difference between an implicitly unwrapped optional, and the type itself?
For example,
var s:String!
var s2: String
Aren't these two exactly the same? They represent a String that can't be nil, so why on Earth do we need the ! thing?
The implicitly unwrapped optional is an optional, in fact you can assign a nil
value
var s: String! = nil
But declaring as implicitly unwrapped, you don't have to append ?
every time you use it, so, as its name states, it is implicitly unwrapped because it is supposed to contain a non nil value.
Consequence: if an implicitly unwrapped is nil, most likely when you use it in your code a runtime exception will be generated - for instance:
let s: String! = nil
var s1: String = s // Execution was interrupted, reason: EXC_BAD_INSTRUCTION ...
The question could turn into: why do implicitly unwrapped optionals exist? The answer is that they are needed to Resolving Strong Reference Cycles Between Class Instances, and a few other cases.
I would personally avoid declaring implicitly unwrapped variables in my code, unless I have a very good reason (such as to solve reference cycles, as mentioned above)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With