swift 推迟特殊性 : why is code in case:defer is invoked before the end of the switch scope?

标签 swift

case .foo:
    defer {
       baz()
    }
    fallthrough
case .bar:

在我们进入酒吧场景之前就到达了 baz()。 这是预期的结果还是编译器出错了? 我期望 baz() 在切换结束时被调用 作用域还是函数作用域???!!!

最佳答案

case: block 的末尾是该 block 范围的末尾...fallthrough 语句不维护范围。

考虑以下因素:

    defer { print("outer deferred") }

    let t = 1

    switch t {
    case 0:
        print("0")
    case 1:
        print("1")
        defer { print("deferred") }
        fallthrough
    case 2:
        print("2")
    default:
        print("default")
    }

输出将是:

1

deferred

2

outer deferred

现在,考虑一下:

    defer { print("outer deferred") }

    let t = 1

    switch t {
    case 0:
        print("0")
    case 1:
        let str = "hello"
        print("1")
        defer { print("deferred") }
        fallthrough
    case 2:
        print("2")
        print(str)        // <-- error
    default:
        print("default")
    }

编译器会告诉您 str 是一个未解析的标识符,因为它是在 case 1: 内创建的,但不再在 case 2 的范围内: .

关于 swift 推迟特殊性 : why is code in case:defer is invoked before the end of the switch scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610020/

相关文章:

ios - 使用 Alamofire 4 的 header 授权最佳实践,具有全局 401 代码捕获

ios - UILabel 调整字体以适合文本

ios - 是否可以远程打开我的 iOS 应用程序?

ios - 如何将特定的 ViewController 分配给 UIView(在 UICollectionView 中)?

ios - 带正文的 Swift HTTP POST

ios - 如何声明实现多个协议(protocol)的参数

SwiftUI:防止长词断字

ios - UISearchBar - 切换 UITableView

ios - 没有更多上下文swift4,表达式类型不明确

ios - 设置SKSpriteNode的可触摸区域