DevPrep

All topics › Design patterns

Singleton

Junior PRO

Essence

Singleton is a creational pattern: a class has exactly one instance, created lazily, with global access. The defining ingredients are static let shared and private init(): without a private initializer it is not a singleton but a "shared instance", a convenient default next to which other instances can be created. UserDefaults.standard, FileManager.default, URLSession.shared and NotificationCenter.default are shared instances (you can create UserDefaults(suiteName:) or FileManager()); true singletons are UIApplication.shared and UIDevice.current. This is a classic trick question.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store