Having hard time implement a simple singleton in swift

You can’t just have var = xxx in an init. The variable has to be declared at the class top level.

Example of using your singleton:

class Globals {

    static let sharedInstance = Globals()

    var max: Int

    private init() {
        self.max = 100
    }

}

let singleton = Globals.sharedInstance

print(singleton.max) // 100

singleton.max = 42

print(singleton.max) // 42

When you need to use the singleton in another class, you just do this in the other class:

let otherReferenceToTheSameSingleton = Globals.sharedInstance

Update following Martin R and Caleb’s comments: I’ve made the initializer private. It prevents, in other Swift files, the initialization of Globals(), enforcing this class to behave as a singleton by only being able to use Globals.sharedInstance.

Leave a Comment