Weak Singleton in Swift
Countless articles have been written arguing whether the Singleton pattern is an anti-pattern or not. I'm not going to get into that argument, though I do think there are valid use-cases for it from a pragmatic point of view. I recently wanted to implement such a singleton in Swift, but with the twist that if it isn't referenced from anywhere it will be released from memory; a so-called weak singleton. Fire it up in a playground, and see how it works :)
// The type being stored in the singleton
class Resource {
let name: String
init () {
print("init") // Called once
name = "I'm a resource"
}
deinit {
print("deinit") // Called once
}
}
// The class serving up the singleton
class SharedResource {
static weak var weakInstance: Resource?
static var sharedInstance: Resource {
get {
if let instance = weakInstance {
return instance
} else {
let newInstance = Resource()
weakInstance = newInstance
return newInstance
}
}
}
}
// Reference the singleton from 3 different variables
// Note that init() will be called just one time
var str: Resource? = SharedResource.sharedInstance
var str2: Resource? = SharedResource.sharedInstance
var str3: Resource? = SharedResource.sharedInstance
// Dereference the singleton
// After the last variable dereferences it, deinit will be called
str = nil
str2 = nil
str3 = nil