“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量

“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量,第1张

概述参见英文答案 > Whither dispatch_once in Swift 3?                                    6 >             Using a dispatch_once singleton model in Swift                                    25个 迁移到Swift 3时,dispatch 参见英文答案 > Whither dispatch_once in Swift 3?6
> Using a dispatch_once singleton model in Swift25个
迁移到Swift 3时,dispatch_once_t有问题.

根据Apple’s migration guide:

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() }()}
总结

以上是内存溢出为你收集整理的“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量全部内容,希望文章能够帮你解决“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1040068.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存