参见英文答案 >
Whither dispatch_once in Swift 3?6
> Using a dispatch_once singleton model in Swift25个
迁移到Swift 3时,dispatch_once_t有问题.
原文链接:https://www.f2er.com/swift/319745.html> Using a dispatch_once singleton model in Swift25个
迁移到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.
所以我想迁移这个代码.所以在迁移之前:
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! }
迁移后,按照Apple的指南(手动迁移),代码如下所示:
class var sharedInstance: CarsConfigurator { struct Static { static var instance: CarsConfigurator? static var token = {0}() } _ = Static.token return Static.instance! }
但是当我运行这个访问返回时,我得到以下错误Static.instance !:
fatal error: unexpectedly found nil while unwrapping an Optional value
我从这个错误中看到,实例成员为零,但为什么呢?我的迁移有问题吗?