首页 文章

带有“?”(问号)和“!”(感叹号)的Swift变量装饰

提问于
浏览
97

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

我不明白的是,用 ! 设置一个变量是做什么的,因为我的印象是这个"unwraps"来自一个可选的值 . 我想通过这样做,你保证有一个值来展开该变量,这就是为什么在IBActions上你会看到它被使用 .

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

var aShape : CAShapeLayer!

为什么/我什么时候会这样做?

1 回答

  • 136

    在类型声明中, ! 类似于 ? . 两者都是可选的,但是 ! 是“implicitly unwrapped" optional”,这意味着您不必打开它来访问该值(但它仍然可以为零) .

    这基本上是我们在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
    }
    

相关问题