Swift Language Singleton


Example

Singletons are a frequently used design pattern which consists of a single instance of a class that is shared throughout a program.

In the following example, we create a static property that holds an instance of the Foo class. Remember that a static property is shared between all objects of a class and can't be overwritten by subclassing.

public class Foo
{
    static let shared = Foo()
    
    // Used for preventing the class from being instantiated directly
    private init() {}
    
    func doSomething()
    {
        print("Do something")
    }
}

Usage:

Foo.shared.doSomething()

Be sure to remember the private initializer:

This makes sure your singletons are truly unique and prevents outside objects from creating their own instances of your class through virtue of access control. Since all objects come with a default public initializer in Swift, you need to override your init and make it private. KrakenDev