关于swift3:’dispatch_once_t’在Swift中不可用:改为使用延迟初始化的全局变量

'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals instead

本问题已经有最佳答案,请猛点这里访问。

我在迁移到Swift 3时遇到了dispatch_once_t的问题。

根据苹果的迁移指南:

The free function dispatch_once is no longer available in Swift. In
Swift, you can use lazily initialized globals or static properties and
get the same thread-safety and called-once guarantees as dispatch_once
provided. Example:

let myGlobal = { … global contains initialization in a call to a closure … }()

_ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.

所以我想迁移这个代码。所以在迁移之前:

1
2
3
4
5
6
7
8
9
10
11
12
13
class var sharedInstance: CarsConfigurator
{
    struct Static {
        static var instance: CarsConfigurator?
        static var token: dispatch_once_t = 0
    }

    dispatch_once(&Static.token) {
        Static.instance = CarsConfigurator()
    }

    return Static.instance!
}

迁移之后,按照苹果的指导原则(手动迁移),代码如下:

1
2
3
4
5
6
7
8
9
10
11
class var sharedInstance: CarsConfigurator
{
    struct Static {
        static var instance: CarsConfigurator?
        static var token = {0}()
    }

    _ = Static.token

    return Static.instance!
}

但是,当我运行此命令时,在访问return Static.instance!时会出现以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

我从这个错误中看出,instance成员是nil成员,但为什么呢?我的迁移有问题吗?


这段代码过于冗长,即使它在Swift2中是有效的。在Swift 3中,Apple通过关闭强制您使用延迟初始化:

1
2
3
class CarsConfigurator {
    static let sharedInstance: CarsConfigurator = { CarsConfigurator() }()
}