上QQ阅读APP看书,第一时间看更新
Implicitly unwrapped optionals
The following code will produce an error:
let a:Int
a = 3
let b: Int = a
let c: Int = a * 2
Even though variable a does contain a value, its type is still an optional Int, and cannot be assigned to the values of b and c, which are declared to be non-optionals of type Int.
Rather than force unwrap a each time we use it, we can declare it to be an implicitly unwrapped optional, using the ! operator, which kind of bakes the unwrapping into the variable itself:
var a:Int!
a = 3
let b: Int = a
let c: Int = a * 2
We would only do this when we can guarantee that a can never be nil, but there are occasions when we can do just that. The IBOutlet from an Interface Builder storyboard is a common example.
If an implicitly unwrapped optional is unexpectedly nil at runtime, your program will, of course, drop dead on the spot.