参见英文答案 >
Whither dispatch_once in Swift 3?6
> Using a dispatch_once singleton model in Swift25个
迁移到Swift 3时,dispatch_once_t有问题.
> 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
我从这个错误中看到,实例成员为零,但为什么呢?我的迁移有问题吗?
即使Swift 2中有效,该代码过于冗长.在Swift 3中,Apple强制您通过关闭来使用延迟初始化:
class CarsConfigurator { static let sharedInstance: CarsConfigurator = { CarsConfigurator() }() }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。