How to create a singleton in Swift

Oscar de la Hera Gomez
A flower that represents Swift next to a flower that represents XCode. Beneath it sits the text that states 'Swift Singleton'.

A step by step tutorial on creating a singleton in Swift (iOS). Github repository available.

The following tutorial builds on our starter project and covers the creation of a singleton through the example of a LanguageCoordinator.

If you are looking for the specific code, please jump to Step Four.

Step One: Create the folder for the singleton

A screenshot showing the folder we created for the LanguageCoordinator singleton.

We recommend that you create a folder for your singleton and all associated functionality.

Step Two: Create the file for the singleton

A screenshot showing how to create a swift file.

Select your folder and press Command + N to create a file and press next.

Please note that this assumes that a Swift file is auto selected.

Step Three: Name & create the singleton file

A screenshot showing how to name and save a Swift file.

Name your singleton and press Create.

Step Four: Code your singleton

A screenshot showing you how to create the Singleton code.

Code your class and functionality.

To make it a singleton, add the following line - which makes the singleton accessible via the .shared parameter - i.e. LanguageCoordinator.shared. You can call this whatever you like, i.e. singleton would be accessed by LanguageCoordinator.singleton.

Alternatively, copy and add to the gist below.

Step Five: Verify

A screenshot showing how we verified the singleton through the view controller, by calling the initialize function.

Call a function or variable within your singleton within a part of your app to verify that it's been setup correctly.

In our example we call the LanguageCoordinator singleton initialize function from the ViewController on ViewDidLoad.

Looking for more XCode tutorials ?

Here's a range of resources that might interest you.

Any Questions

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.

delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details