Or, "How the fuck to I make a singleton?"
One of the patterns that seems to be very common in Cocoa is the sharedInstance pattern. You can see it in a few of the native classes to UIKit and Cocoa. For example:
- In
UIApplicationyou havesharedApplicationwhich returns the current application. You'll use it when wanting to display the network indicator for instance. - On OS X
NSNotificationCenterhas thedefaultCenter. NSUserNotificationCenterhas thedefaultUserNotificationCenterwhich again follows this principal.
While the above may not share the same name, the all follow the same pattern and return an instance that is common across the whole of your application.
In terms of naming conventions, I've been naming them
sharedInstanceorsharedTypewhere type is the name of the object type I want to share i.e.sharedTracksorsharedManager
In Swift 1.2+ creating one of these couldn't be simpler. It's literally one line! Which, when you compare it to how you'd accomplish it in Obj-C is pretty mind blowing.
To create a shared instance you just need to add a static property to your class:
static let sharedInstance = ClassType()
That's it! Now you can access this anywhere in your application with the following:
ClassType.sharedInstance
✌️