Singletons in Swift

Ahmed Fathi
2 min readJul 6, 2018

--

Singleton is a creational design pattern that usually used with object-oriented structures, and it’s commonly used in iOS development. It is something every iOS developer should know.

Singletons are mainly used to ensure that there is one and only one live instance of your class at anytime of your app lifetime and that instance have a global access.

Haven’t that remind you of something? AppDelegate you’ve been using is actually a singleton, there is only one instance of it, you can’t create more instances and you can access it from anywhere in your app.

Build your own Singleton

let us build a simple singleton together to demonstrate the idea.

Start by creating new file User.swift and typing a very simple user class that has only username and password:

class User {
var username: String?
var password: String?
}

User class is usually a singleton class as we only have one user all the time and we need to access it from everywhere. Now, let us continue by adding the initialization method:

class User {
var username: String?
var password: String?

private init() {
// You can do whatever initializtion you want here
}
}

Why private init()? using private initializer prevents anyone from creating instance of the User class.

Now, we need to create our shared instance and give it a global access

class User {
var username: String?
var password: String?

static var shared = User()

private init() {
// You can do whatever initializtion you want here
}
}

We created an instance of the User class using our private initializer we just created and stored in a variable named shared. Using static helps you to access it directly by typing User.shared, and one other tip is using static also makes it lazy initialization, which means this instance won’t be created with app launch, but it will be created at the first time you access it, which removes that burden of the app launch.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

// Setting data in our singleton user
User.shared.username = "John"
User.shared.password = "1234"

// Accessing data from the singleton user
print(User.shared.username ?? "no username") // prints John
print(User.shared.password ?? "no password") // prints 1234
}
}

And that’s it. You have just created you own singleton. It’s good practice to think of other singleton classes you’ve been using without noticing like AppDelegate.

In the real world projects you might want to save user data in something persistent like UserDefaults, but it’s not secure enough to save sensitive information about the user, so you might have to use Keychain.

Enjoy your coding!

--

--