How to write a singleton in Swift

I’m as opposed to singletons as anyone else in general due to the fact that they make testing harder, but sometimes, like when managing access to a local SQLite database, I want to make sure there’s only one instance of the class that purges old records from it. So a singleton seems to make sense. But how do we do that in Swift?

The static let here will only instantiate our SQLiteManager once, and the private initializer ensures that no one else calls init on our SQLiteManager.

Now we can call SQLiteManager.shared.purgeObsoleteRecords() and get rid of those old bits we don’t need any more, freeing up some storage for our user.

Get your free guide to getting started with Swift

In this 5 lesson email course, you'll build a solid foundation in Swift as you learn how to cast objects safely, work with optionals, parse JSON without crashing, build a REST API client, and write unit tests to uncover problems early. You'll be building rock-solid REST apps in no time.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit