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?
class SQLiteManager {
static let shared = SQLiteManager()
private init() {}
}
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.