Learning w/ Swift

Singletons: what are they and when to use one

Singletons restrict a class to a single instance, and provide a global point of access to that instance.

Singletons are:

  • Ideal for managing a limited or shared resource, such as a database connection, thread pool, or configuration settings.
  • Ideal for global state use cases, such as settings, preferences, or user authentification purposes.
  • Often, but not always lazily initialized, and don’t actually get created until they are requested.
  • Can be used for a centrilized place for logging, tracing, or monitoring.
  • Caching frequently used data.

Singletons can also be overused, making it difficult undestand and maintain, as well as test and refactor code.