Creating a sharedInstance in Swift

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 UIApplication you havesharedApplication which returns the current application. You'll use it when wanting to display the network indicator for instance.
  • On OS X NSNotificationCenter has the defaultCenter.
  • NSUserNotificationCenter has the defaultUserNotificationCenter which 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 sharedInstance or sharedType where type is the name of the object type I want to share i.e. sharedTracks or sharedManager

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

✌️

Work With Us! We're currently accepting new projects at Cocoon. If you have a cool new thing you want us to help with, feel free to drop me a line ✌️

About Stephen Radford

Software Engineer. I take a few photos when I'm not stuck behind a keyboard too.

Leicester, UK http://stephenradford.co.uk

Comments