#4: Singletons 🚹


Singletons are a design pattern describing globally accessible instances of objects.

They should only be used when we need to read and/or write some state globally and possibly from other threads.

class VehicleManager {
  static let sharedManager = VehicleManager()

  var cars: [Car] = []

  init() {
    // init some (likely) global state

With a singleton, there's a function that can be called from anywhere. In this case it's VehicleManager.sharedManager.

A great side effect is that the initializer for VehicleManager() isn't called until we access .sharedManager the first time.

Singletons TLDR;

  • 👍 Globally accessible
  • 👍 Thread-safe
  • 👍 Lazily initialized
  • 😭 Technique shown here requires Swift 1.2 or later