Singleton and Lazy in Swift
Singleton in Swift
http://krakendev.io/blog/the-right-way-to-write-a-singleton
class TheOneAndOnlyKraken {
static let sharedInstance = TheOneAndOnlyKraken()
}
In Swift, you can simply use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:
class Singleton {
static let sharedInstance = Singleton()
}
If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
class TestClass {
// both of below will init once
// init at first
let a: Int = {
print("aaa")
return 1+2
}()
// lazy init
lazy var b: Int = {
print("bbb")
return 2+3
}()
}