---
title: "#4: Singletons 🚹"
url: https://littlebitesofcocoa.com/4-singletons
author: Jake Marsh
published: 2015-05-21
topics: ["Swift","Techniques"]
description: "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..."
---

# #4: Singletons 🚹

By Jake Marsh, May 21, 2015. HTML: https://littlebitesofcocoa.com/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**.

``` swift
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
