Making some code only run once

Swift 1,2:

static var token: dispatch_once_t = 0

dispatch_once(&token) {
  NSLog("Do it once")
}

Objective-C

static dispatch_once_t once;
dispatch_once(&once, ^ {
  NSLog(@"Do it once");
});

Swift 3,4:

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
Apple doc

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.

Leave a Comment