Making a Singleton in Swift

A Singleton is a design pattern that only allows the instantiation of a single instance of a class.

Here’s a simple way of setting up a Singleton in Swift.


let sharedThing = MySingleton()

class MySingleton {
    var name = "Eric"
}

This can be accessed anywhere in your code.

sharedThing.name has default initialisation value “Eric” and can be set with a line such as;


    sharedThing.name = "Lynda"

A lot less typing than was needed to do the same thing in Objective C !

Leave a comment