Whither dispatch_once in Swift 3? Whither dispatch_once in Swift 3? swift swift

Whither dispatch_once in Swift 3?


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 uselet foo = SomeClass()// global var, same thing happens here// even though the "initializer" is an immediately invoked closurevar bar: SomeClass = {    let b = SomeClass()    b.someProperty = "whatever"    b.doSomeStuff()    return b}()// ditto for static properties in classes/structures/enumsclass 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.


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 what it looks like at the 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 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.


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