带有“?"的 Swift 变量装饰(问号)和“!"(感叹号) [英] Swift variable decorations with "?" (question mark) and "!" (exclamation mark)

查看:29
本文介绍了带有“?"的 Swift 变量装饰(问号)和“!"(感叹号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我不明白的是,使用 ! 设置变量在做什么,因为我的印象是这会从可选中解开"一个值.我认为通过这样做,您可以保证在该变量中有一个要解包的值,这就是为什么在 IBActions 上看到它被使用的原因.

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.

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

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?

推荐答案

在类型声明中,! 类似于 ?.两者都是可选的,但 !隐式解包" 可选,这意味着您不必解开它来访问值(但它仍然可以为零).

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

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

用法:

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

这篇关于带有“?"的 Swift 变量装饰(问号)和“!"(感叹号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆