How to create a singleton in Swift

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 07/12/2022 at 15:00
Last Updated on 08/27/2022 at 11:54
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.

Download open source projectHow to create a SwiftLint enabled Swift Xcode project

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.

Download open source project

Looking for more XCode tutorials ?

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

How to create a SwiftLint enabled Swift Xcode ProjectHow to create a structured Xcode projectHow to add a Swift Package Manager package dependencyRecommendations for debugging via the console in XCode

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.

SubscribeInquireView All PostsView All ServicesView All Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe