Singleton Pattern

Introduction

Welcome to the last lesson of Object Oriented Swift. You will learn how to create an object that exists anywhere. The object is like me. There is only one Bob. I’m omnipresent.

Definition of Singleton

A singleton is an object which is instantiated exactly once.

Design Class

Create a class called, AccountManager. It has a static property with an object of the class itself.

  1. class AccountManager {
  2. static let sharedInstance = AccountManager()
  3. var userInfo = (ID: "bobthedev", Password: 01036343984)
  4. // Networking: communicating server
  5. func network() {
  6. // get everything
  7. }
  8. private init() { }
  9. }

The private prevents initialization outside of the AccountManager class. If you wish to learn more, you may read The Complete Understanding of Access Control in Swift

Access Object

  1. AccountManager.sharedInstance.userInfo
  2. // (ID "bobthedev", Password 01036343984)
  3. // ViewController One
  4. AccountManager.sharedInstance.userInfo.ID // "bobthedev"
  5. // ViewController Two
  6. AccountManager.sharedInstance.userInfo.ID = "bobleesj"
  7. // ViewController Three
  8. AccountManager.sharedInstance.userInfo.ID // "bobleesj'

In each view controller, you have access to only one AccountManager().

Examples

The iOS ecosystem often use the singleton pattern for developers to access the universal object. A few examples include, UIApplication, UserDefault, NSNotification. If you wish to learn more about these classes, you may sign up for the upcoming course: The UIKit Fundamentals with Bob.

Source Code

2008_singleton_pattern.playground

Resources

The Complete Understanding of Access Control in Swift 3

Conclusion

You’ve learned the definition of Singleton. Again, think of me. There is only one Bob the Developer.

Often developers avoid the singleton pattern at all cost. It exists everywhere, and when you have a number of them, it becomes difficult to track. So, I’d recommend not to overuse the pattern. If you wish to know how to work with UIApplication, UserDefault, and NSNotification along with Protocols, you may sign up for the upcoming course and receive updates from me.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.