在Swift中如果想搞类的单例模式,那么在初始化的时候一般会使用just one time执行的方式,我们使用dispatch_once_t配合调用dispatch_once方法,一般的代码如下:

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.")
    }
}

不过在Swift3中会提示此法行不通,dispatch_xxx已废弃,use lazily initialized globals instead.

原来自从swift 1.x开始swift就已经开始用dispatch_one机制在后台支持线程安全的全局lazy初始化和静态属性.所以static var背后已经在使用dispatch_once了.网友的解释是:

So the static var above was already using dispatch_once, which makes it sort of weird (and possibly problematic to use it again as a token for another dispatch_once. In fact there's really no safe way to use dispatch_once without this kind of recursion, so they got rid of it. Instead, just use the language features built on it

所以现在的swift3中干脆把dispatch_once显式的取消了.

我们再Swift3中若要想实现原来dispatch_once的机制可以用以下几种办法:

1.使用全局常量

let foo = SomeClass()

2.带立即执行闭包初始化器的全局变量:

var bar: SomeClass = {
    let b = SomeClass()
    b.someProperty = "whatever"
    b.doSomeStuff()
    return b
}()

3.类,结构,枚举中的静态属性:

class MyClass {
    static let singleton = MyClass()
    init() {
        print("foo")
    }
}

你还可以直接创建一个全局的变量或静态属性来达到没有结果的just one time:

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

如果你觉得这都不和你的胃口,你可以在需要调用justAOneTimeThing的地方直接调用它就是啦:

func doTheOneTimeThing() {
    justAOneTimeThing
}

所以在Swift3中推荐使用如下方法来完成一个单例:

class Foo{
    private static let sharedInstance = Foo()
    class var sharedFoo {
        return sharedInstance
    }
}
04-27 23:48