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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s