Swift可选链接

示例

您可以使用“可选链接”来调用方法,访问属性或下标可选。这是通过?在给定的可选变量和给定的成员(方法,属性或下标)之间放置a来完成的。

struct Foo {
    func doSomething() {
        print("你好,世界!")
    }
}

var foo : Foo? = Foo()

foo?.doSomething() // prints "你好,世界!" as foo is non-nil

如果foo包含一个值,doSomething()将对其进行调用。如果foo为nil,则不会发生任何不好的事情-代码将仅静默失败并继续执行。

var foo : Foo? = nil

foo?.doSomething() // 不会被调用,因为foo为nil

(这类似于nil在Objective-C中向发送消息到)

之所以这样命名“可选链接”,是因为“可选性”将通过您调用/访问的成员传播。这意味着与可选链接一起使用的任何成员的返回值都是可选的,无论它们是否键入为可选。

struct Foo {
    var bar : Int
    func doSomething() { ... }
}

let foo : Foo? = Foo(bar: 5)
print(foo?.bar) // 可选的(5)

尽管它是可选的,但这里foo?.bar返回的是Int?evenbar是非foo可选的。

随着可选性的传播,使用可选链接调用时,返回的方法Void将返回Void?。这对于确定是否调用该方法很有用(并因此确定可选方法是否具有值)。

let foo : Foo? = Foo()

if foo?.doSomething() != nil {
    print("foo is non-nil, and doSomething() was called")
} else {
    print("foo is nil, therefore doSomething() wasn't called")
}

在这里,我们将比较Void?返回值,nil以确定是否调用了该方法(因此是否foo为非nil)。