Skip to content

Latest commit

 

History

History
54 lines (36 loc) · 1.11 KB

Singletons.md

File metadata and controls

54 lines (36 loc) · 1.11 KB

Singletons

Swift uses singletons when it wants only one instance of a class to exist.

let defaults = UserDefaults.standard
let sharedURLSession = URLSession.shared

A Singleton is Swift is implemented with the static key word

class Singleton {
    static let sharedInstance = Singleton()
}

But you can create also create thsm like this with a private constructor

class NetworkManager {

    static let shared = NetworkManager(baseURL: API.baseURL)

    let baseURL: URL

    private init(baseURL: URL) {
        self.baseURL = baseURL
    }

}

Or more simply with a closure like this

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

The advantage of the private constructor is no one can accidentally create a non-shared instance.

Links that help