Reputation: 41510
I was under the impression that implicitly unwrapped optional will cause a runtime exception when used and it is nil. But the following code works without runtime exception, why?
var str:String?
println(str!) // Crashes as expected
var str:String! // Implicitly unwrapped
println(str) // Does not crash, not what I expect - it prints nil
Upvotes: 0
Views: 92
Reputation: 122489
An implicitly-unwrapped optional is only forcibly unwrapped in a situation which expects a non-optional. println()
accepts all types, including optionals, and so there is no need to forcibly unwrap it before passing to println()
. Since it is not unwrapped, it does not crash.
Upvotes: 0
Reputation: 72770
It prints the variable as enum (i.e. optional), because internally an optional is enum Optional<T>
.
More precisely, I presume it uses the debugDescription
property, in fact this is what happens:
var str:String?
println(str) // Prints "nil"
str.debugDescription // Prints "nil"
Upvotes: 1