fuzzygoat fuzzygoat - 7 months ago 13
Swift Question

Accessing valueless implicitly unwrapped optional?

I am curious about the way implicitly unwrapped optionals work, in the Apple reference book - The Swift Programming Language it states:


“If you try to access an implicitly unwrapped optional when it does
not contain a value, you will trigger a runtime error. The result is
exactly the same as if you place an exclamation mark after a normal
optional that does not contain a value.”


If I try and access a valueless optional without an exclamation mark you get an error as stated above.

var optionalVar:String?
println("VAR: \(optionalVar!)")


If however you try an access an implicitly unwrapped optional that does not contain a value the println outputs
VAR: nil
which is not what is stated above.

var implicitOpt:String!
println("VAR: \(implicitOpt)")


Can anyone clarify this, is it badly worded docs, me miss understanding, a bug?

Answer

Thing is that you are not unwrapping the value in this case, but printing unwrapped optional as special type. Weird, I know. Try casting it to normal String and it will crash if nil:

var implicitOpt: String!
println("VAR: \(implicitOpt as String)")

The following lines are equal:

var implicitOpt: ImplicitlyUnwrappedOptional<String>
var implicitOpt: String!

ImplicitlyUnwrappedOptional conforms to Printable protocol. So the string interpolation

"\(implicitOpt)"

will call description on ImplicitlyUnwrappedOptional instance and not String instance. Thats why optional is not unwrapped in this case.