带“ ?”(问号)和“ !”(叹号)的快速变量装饰

我知道在 Swift 中所有的变量都必须设置一个值,通过使用可选项,我们可以设置一个变量,最初设置为 nil

我不明白的是,使用 !设置变量是在做什么,因为我的印象是,这是从一个可选的值“打开”一个值。我认为通过这样做,您可以保证在该变量中有一个值要展开,这就是为什么在 IBActions 等应用程序中可以看到使用它的原因。

简单地说,当你这样做的时候,初始化的变量是什么:

var aShape : CAShapeLayer!

我为什么要这么做?

26644 次浏览

In a type declaration the ! is similar to the ?. Both are an optional, but the ! is an "implicitly unwrapped" optional, meaning that you do not have to unwrap it to access the value (but it can still be nil).

This is basically the behavior we already had in objective-c. A value can be nil, and you have to check for it, but you can also just access the value directly as if it wasn't an optional (with the important difference that if you don't check for nil you'll get a runtime error)

// 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

Usage:

// 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
}