When using lazy initialized globals it may make sense for some one-time initialization, this does not make sense for other types. It is very useful to use lazy initialized globals for things like single player games, it doesn't make much sense for things like swizzle setting protection.
Here is a Swatch 3 style implementation of dispatch_once style:
public extension DispatchQueue { private static var _onceTracker = [String]() public class func once(token: String, block:@noescape(Void)->Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } }
Here is a usage example:
DispatchQueue.once(token: "com.vectorform.test") { print( "Do This Once!" ) }
or using UUID
private let _onceToken = NSUUID().uuidString DispatchQueue.once(token: _onceToken) { print( "Do This Once!" ) }
As we are in the process of moving from fast 2 to 3, here is an example implementation of swift 2:
public class Dispatch { private static var _onceTokenTracker = [String]() public class func once(token token: String, @noescape block:dispatch_block_t) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTokenTracker.contains(token) { return } _onceTokenTracker.append(token) block() } }
Tod Cunningham Jul 11 '16 at 15:49 2016-07-11 15:49
source share