Last active
August 13, 2016 17:08
-
-
Save SpacyRicochet/1fd957570eaa4d0bb2905c393d6566ba to your computer and use it in GitHub Desktop.
Some patterns for Singletons in Swift 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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