Swift可变装饰用“?”(问号)和“!””(感叹号)

时间:2021-02-07 22:24:02

I understand that in Swift all variables must be set with a value, and that by using optionals we can set a variable to be set to nil initially.

我理解在Swift中,所有变量都必须设置一个值,通过使用选项,我们可以将变量设置为nil。

What I don't understand is, what setting a variable with a ! is doing, because I was under the impression that this "unwraps" a value from an optional. I thought by doing so, you are guaranteeing that there is a value to unwrap in that variable, which is why on IBActions and such you see it used.

我不明白的是,用a设置变量是什么意思!之所以这么做,是因为我觉得这个“解开”了一个可选值。我认为通过这样做,您可以保证在该变量中有一个要展开的值,这就是为什么要在ibaction上使用它。

So simply put, what is the variable being initialized to when you do something like this:

简单地说,当你这样做的时候变量被初始化了:

var aShape : CAShapeLayer!

And why/when would I do this?

我为什么要这样做?

1 个解决方案

#1


129  

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).

在类型声明中!与?相似。两者都是可选的,但是!是一个“隐式解包”可选选项,这意味着您不必展开它来访问值(但它仍然可以是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)

这就是objective-c中我们已经有的行为。一个值可以是nil,你必须检查它,但你也可以直接访问这个值,就好像它不是一个可选的(重要的区别是如果你不检查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

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
}

#1


129  

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).

在类型声明中!与?相似。两者都是可选的,但是!是一个“隐式解包”可选选项,这意味着您不必展开它来访问值(但它仍然可以是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)

这就是objective-c中我们已经有的行为。一个值可以是nil,你必须检查它,但你也可以直接访问这个值,就好像它不是一个可选的(重要的区别是如果你不检查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

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
}