Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Last active December 11, 2017 03:18
Show Gist options
  • Save evgeniyd/82fcbd15c4727e040d9b58380888110c to your computer and use it in GitHub Desktop.
Save evgeniyd/82fcbd15c4727e040d9b58380888110c to your computer and use it in GitHub Desktop.
Swift 3: dispatch_once workarounds overview
import Foundation
private let justAOneTimeThing: () = {
print("\(GlobalOnceClass.self): Do This once")
}()
public final class GlobalOnceClass {
public init() {
}
public func someAction() {
justAOneTimeThing
}
}
import Foundation
public final class InitializeOnceClass: NSObject {
private static var __once: () = {
print("\(InitializeOnceClass.self): Do This once")
}()
public override class func initialize() {
_ = InitializeOnceClass.__once
}
public func someAction() {
_ = InitializeOnceClass.__once
}
}
import Foundation
public final class LazyOnceClass {
private lazy var foo: Void = {
print("\(LazyOnceClass.self): Do this once")
}()
public init() {
}
public func someAction() {
_ = foo
}
}
//: [Previous](@previous)
import Foundation
print("> Test: LazyOnceClass")
let a = LazyOnceClass()
a.someAction()
a.someAction()
a.someAction()
let b = LazyOnceClass()
b.someAction()
b.someAction()
b.someAction()
// prints:
// "LazyOnceClass: Do this once"
// "LazyOnceClass: Do this once"
print("> Test: GlobalOnceClass")
let c = GlobalOnceClass()
c.someAction()
c.someAction()
c.someAction()
let d = GlobalOnceClass()
d.someAction()
d.someAction()
d.someAction()
// prints:
// "GlobalOnceClass: Do This once"
print("> Test: InitializeOnceClass")
let e = InitializeOnceClass()
e.someAction()
e.someAction()
e.someAction()
let f = InitializeOnceClass()
f.someAction()
f.someAction()
f.someAction()
// prints:
// "InitializeOnceClass: Do This once"
//: [Next](@next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment