Whither dispatch_once in Swift 3?

瘦欲@ 提交于 2019-11-26 20:04:34

Since Swift 1.x, Swift has been using dispatch_once behind the scenes to perform thread-safe lazy initialization of global variables and static properties.

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:

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

So that's all great if you've been using dispatch_once for one-time initialization that results in some value -- you can just make that value the global variable or static property you're initializing.

But what if you're using dispatch_once to do work that doesn't necessarily have a result? You can still do that with a global variable or static property: just make that variable's type Void:

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

And if accessing a global variable or static property to perform one-time work just doesn't feel right to you -- say, you want your clients to call an "initialize me" function before they work with your library -- just wrap that access in a function:

func doTheOneTimeThing() {
    justAOneTimeThing
}

See the migration guide for more.

The other answers here and around the interwebs are pretty great, but I feel this little tidbit should also be mentioned:

The great thing about dispatch_once was how optimized it was, essentially nixing the code after the first run in a way that I hardly understand, but am reasonably assured that would be that much faster than setting and checking a (real) global token.

While the token thing could be reasonably implemented in Swift, having to declare yet another stored boolean isn't all that great. Not to mention thread-unsafe. As the doc says, you should use a "lazily initialized global." Yeah, but why clutter up the global scope, right?

Until somebody convinces me of a better method, I tend to declare my do-once closure inside the scope I'll be using it in, or reasonably close thereto, as follows:

private lazy var foo: Void = {
    // Do this once
}()

Basically I'm saying that "When I read this, foo should be the result of running this block." It behaves the exact same way as a global let constant would, just in the right scope. And prettier. Then I'd call it wherever I'd like, by reading it into something that'll never be used otherwise. I like Swift's _ for that. Like so:

_ = foo

This really cool quirk has actually been around a while, but hasn't seen much love. It basically leaves the variable alone at runtime, as an uncalled closure, until something wants to see its Void result. On read, it calls the closure, throws it away and keeps its result in foo. Void uses practically nothing memory-wise, so subsequent reads (i.e. _ = foo) do nothing on the CPU. (Don't quote me on that, somebody please check up on the assembly to be sure!) Have as many as you like, and Swift basically quits caring about it after the first run! Lose that old dispatch_once_t, and keep a lot of your code as pretty as when you first opened it Christmas day!

My one issue is that you can set foo to something else before its first read, and then your code will never be called! Hence the global let constant, which prevents that. Thing is, constants in class scope don't play well with self, so no playing with instance variables... But seriously, when do you set anything to Void anyway??

That, and you'd need to specify the return type as Void or (), else it'll still complain about self. Who'da thunk?

And lazy is just to make the variable as lazy as it should be, so Swift doesn't run it straight off on init().

Pretty snazzy, so long as you remember not to write to it! :P

While the "lazy var" pattern allows me to stop caring about dispatch tokens and is generally more convenient than dispatch_once() was, I don't like how it looks at call site:

_ = doSomethingOnce

I would expect this statement to look more like a function call (since it implies action), but it doesn't look so at all. Also, having to write _ = to explicitly discard the result is unnecessary and annoying.

There is a better way:

lazy var doSomethingOnce: () -> Void = {
  print("executed once")
  return {}
}()

Which makes the following possible:

doSomethingOnce()

This might be less efficient (since it calls an empty closure instead of just discarding a Void), but improved clarity is totally worth it for me.

Example for "dispatch_once" in Swift 3.0

Step 1 : Just Replace below code with your Singleton.swift (Singleton class)

// Singleton Class
class Singleton: NSObject { 
var strSample = NSString()

static let sharedInstance:Singleton = {
    let instance = Singleton ()
    return instance
} ()

// MARK: Init
 override init() {
    print("My Class Initialized")
    // initialized with variable or property
    strSample = "My String"
}
}

Singleton Sample Image

Step 2 : Call Singleton from ViewController.swift

// ViewController.swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let mySingleton = Singleton.sharedInstance
        print(mySingleton.strSample)

        mySingleton.strSample = "New String"

        print(mySingleton.strSample)

        let mySingleton1 = Singleton.sharedInstance
        print(mySingleton1.strSample)

    }

ViewController Sample Image

Output like this

My Class Initialized
My String
New String
New String

Compiles under Xcode 8 GA Swift 3

The recommended and elegant way to create a dispatch_once singleton class instance:

final class TheRoot {
static let shared = TheRoot()
var appState : AppState = .normal
...

To use it:

if TheRoot.shared.appState == .normal {
...
}

What do these lines do?

final - so the class cannot be overridden, extended, it also makes the code somewhat faster to run, less indirections.

static let shared = TheRoot() - This line does lazy init, and it only runs once.

This solution is thread safe.

According to the 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 … }()

  // using myGlobal will invoke the initialization code only the first time it is used.
  _ = myGlobal  

Thread-safe dispatch_once:

private lazy var foo: Void = {
    objc_sync_enter(self)
    defer { objc_sync_exit(self) }

    // Do this once
}()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!