Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Some patterns for Singletons in Swift 2
// The easiest pattern. Just use a `static let`, which gets lazy loaded as a bonus.
class Singleton {
static let sharedInstance = Singleton()
func helloWorld() {
print("Hello world")
}
}
Singleton.sharedInstance.helloWorld() // prints "Hello world"
// What if you do want a Singleton that you don't pass around, but still want to change it when testing your code?
// With `setDefaultInstance`, you can replace what `sharedInstance` returns.
// But, this makes it not strictly a singleton, and the pattern is dangerous if you start doing this in production code.
class ChangeableSingleton {
private(set) static var sharedInstance = ChangeableSingleton()
static func setDefaultInstance(instance: ChangeableSingleton) {
sharedInstance = instance
}
var message: String
required init(message: String = "Can I be shorter?") {
self.message = message
}
func helloWorld() {
print(message)
}
}
ChangeableSingleton.sharedInstance.helloWorld() // prints "Can I be shorter?"
ChangeableSingleton.setDefaultInstance(ChangeableSingleton(message: "Shorter is better!"))
ChangeableSingleton.sharedInstance.helloWorld() // prints "Shorter is better!"
//~~
// So what if I have a ton of Singletons? I probably shouldn't, but I really want to!
// Let's make a Protocol with Associated Types (PAT)!
protocol Singletonable {
associatedtype SingletonType
static var sharedInstance: SingletonType { get }
}
class PATSingleton: Singletonable {
private(set) static var sharedInstance = PATSingleton()
}
PATSingleton.sharedInstance
//~~
protocol Printable {
var message: String { get }
func helloWorld()
}
extension Printable {
func helloWorld() {
print(message)
}
}
class PATSingletonWithParameters: Singletonable, Printable {
private(set) static var sharedInstance = PATSingletonWithParameters()
private(set) var message: String
init(message: String = "Message") {
self.message = message
}
}
PATSingletonWithParameters.sharedInstance.helloWorld()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment