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

前端之家收集整理的这篇文章主要介绍了“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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() }()
}
原文链接:https://www.f2er.com/swift/319745.html

猜你在找的Swift相关文章