Using Singletons in Swift

in

There are a number of ways to create and use singletons with Swift, I’ve listed a few here as well as my preferred approach.


Class Constant

This is my preferred approach, it works from Swift 1.2 onwards.

class UserManagerSingleton {
    static let sharedInstance = UserManagerSingleton()
}

Via a nested Struct

You’ll see this used in open source libraries, it’s quite popular and was the preferred way in Swift 1.0. If you need to support Swift 1.0, you have to use this, otherwise you can use the Class Constant method above.

class UserManagerSingleton {
    class var sharedInstance: UserManagerSingleton {
        struct Static {
            static let instance = UserManagerSingleton()
        }
        return Static.instance
    }
}

A global function approach

/// Use it like so: `UserManager().completeLogin()`
func UserManager() -> UserManagerSingleton {
    return UserManagerSingleton.sharedInstance
}

/// Handles the Login/Logout & User Data for Application
class UserManagerSingleton: NSObject {
    static let sharedInstance = UserManagerSingleton()
    // ...
}

You can now call methods directly on the UserManager, instead of littering your code with SomeSingleton.sharedInstance.method().

// Old:
UserManagerSingleton.sharedInstance.completeLogin()

// New:
UserManager().completeLogin()