在swift 3中的dispatch_once?

好吧,所以我发现了新的 Swifty Dispatch API在Xcode 8。我有乐趣使用dispatchQueue.main.async,我已经浏览了Xcode中的dispatch模块,以找到所有新的API。

但是我还使用dispatch_once来确保单例创建和一次性设置等事情不会被执行多次(即使在多线程环境中)…和dispatch_once在新的dispatch模块中是无处不在的吗?

static var token: dispatch_once_t = 0
func whatDoYouHear() {
    print("All of this has happened before,and all of it will happen again.")
    dispatch_once(&token) {
        print("Except this part.")
    }
}
从Swift 1.x开始,Swift已经使用dispatch_once behind the scenes来执行全局变量和静态属性的线程安全延迟初始化。

所以上面的静态var已经使用了dispatch_once,这使得它奇怪(可能有问题再次使用它作为另一个dispatch_once的令牌。事实上,没有这种递归,没有安全的方式使用dispatch_once,所以他们得到相反,只是使用基于它的语言功能

// global constant: SomeClass initializer gets called lazily,only on first use
let foo = SomeClass()

// global var,same thing happens here
// even though the "initializer" is an immediately invoked closure
var bar: SomeClass = {
    let b = SomeClass()
    b.someProperty = "whatever"
    b.doSomeStuff()
    return b
}()

// ditto for static properties in classes/structures/enums
class MyClass {
    static let singleton = MyClass()
    init() {
        print("foo")
    }
}

所以这很棒,如果你一直使用dispatch_once一次性初始化,导致一些价值 – 你可以使该值的全局变量或静态属性你正在初始化。

但是如果你使用dispatch_once来做不一定有结果的工作呢?你仍然可以使用全局变量或静态属性:只是使该变量的类型Void:

let justAOneTimeThing: () = {
    print("Not coming back here.")
}()

如果访问一个全局变量或静态属性来执行一次性工作,就不会感觉到你 – 例如,你希望客户端在使用你的库之前调用“初始化我”函数 – 只是换行在函数中访问:

func doTheOneTimeThing() {
    justAOneTimeThing
}

更多信息参见migration guide

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...