Singletons in Swift

I¬†often find myself using¬†singletons when I’m writing iOS apps, especially in games. They’re a perfect pattern for passing state between game screens and making sure that things like player progress are always up-to-date. In Objective-C I’ve always implemented thread-safe singletons using dispatch_once:

Using Grand Central Dispatch to set up a singleton always felt incredibly low-level, so I was pleased to discover a much nicer implementation using computed properties whilst porting some old code into Swift:

Mark the instance static to make it global, and declare it with let to mark it as a constant. The only weird bit (to me, at least) is wrapping the instance in a struct; Swift doesn’t allow static variables inside computed properties, and wrapping the instance in an internal struct lets us get around that restriction.

You can access the (lazily-created, thread-safe) singleton instance through the sharedInstance getter:

Leave a Reply

Your email address will not be published. Required fields are marked *