在类型声明中,
!类似于
?。两者都是可选的,但是
!是“
隐式展开的”可选的,这意味着您不必解包即可访问值(但它仍然可以为nil)。
这基本上是我们在Objective-C中已经拥有的行为。值 可以
为nil,您必须检查该值,但是您也可以直接访问该值,就好像它不是可选值一样(重要的区别是,如果不检查nil,您将得到一个运行时错误)
// Cannot be nilvar x: Int = 1// The type here is not "Int", it's "Optional Int"var y: Int? = 2// The type here is "Implicitly Unwrapped Optional Int"var z: Int! = 3
用法:
// you can add x and zx + z == 4// ...but not x and y, because y needs to be unwrappedx + y // error// to add x and y you need to do:x + y!// but you *should* do this:if let y_val = y { x + y_val}


