这基本上是我们在objective-c中已经具有的行为 . 一个值可以是nil,你必须检查它,但你也可以直接访问该值,就好像它没有't an optional (with the important difference that if you don' t检查nil你会得到一个运行时错误)
// Cannot be nil
var 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 z
x + z == 4
// ...but not x and y, because y needs to be unwrapped
x + 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
}
1 回答
在类型声明中,
!
类似于?
. 两者都是可选的,但是!
是“implicitly unwrapped" optional”,这意味着您不必打开它来访问该值(但它仍然可以为零) .这基本上是我们在objective-c中已经具有的行为 . 一个值可以是nil,你必须检查它,但你也可以直接访问该值,就好像它没有't an optional (with the important difference that if you don' t检查nil你会得到一个运行时错误)
用法: