• Category: Creational
  • Type: object
  • Motivation: Ensure only one object of a particular class is ever created: there is only one president of a country at a time.

diagram

do {
  let a = President.shared
  let b = President.shared

  print(Unmanaged.passUnretained(a).toOpaque())
  print(Unmanaged.passUnretained(b).toOpaque()) // print same address

  let c = President() // Prevent call -init with private attribute
  print(Unmanaged.passUnretained(c).toOpaque())
}
class President
{
    static let shared: President = {
        let instance = President()
        // Setup code
        return instance
    }()

    private init() {}
}