Swift 5.7的可选解包语法介绍及应用实例

108 阅读1分钟

Swift 5.7 引入了一种新的、更简洁的方式,使用if letguard let 语句来解包可选值。以前,我们总是不得不明确地命名每个解包的值,例如像这样:

class AnimationController {
    var animation: Animation?

    func update() {
        if let animation = animation {
            // Perform updates
            ...
        }
    }
}

但现在,我们可以简单地在if let 语句后删除赋值,Swift 编译器会自动将我们的可选值解包为具有完全相同名称的具体值:

class AnimationController {
    var animation: Animation?

    func update() {
        if let animation {
            // Perform updates
            ...
        }
    }
}

很好!上述新语法也适用于guard 语句:

class AnimationController {
    var animation: Animation?

    func update() {
        guard let animation else {
            return
        }

        // Perform updates
        ...
    }
}

它还可以用来一次解开多个可选项的包装:

struct Message {
    var title: String?
    var body: String?
    var recipient: String?

    var isSendable: Bool {
        guard let title, let body, let recipient else {
            return false
        }

        return ![title, body, recipient].contains(where: \.isEmpty)
    }
}

一个小的,但非常受欢迎的功能。当然,如果我们想这样做的话,我们仍然可以选择明确地命名每一个解包的可选项--无论是出于代码风格的原因,还是如果我们想在解包时给某个可选项一个不同的名字。