Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active March 3, 2021 06:44
Show Gist options
  • Save ahcode0919/d4a1102fc3c43273d7e6b921268a4a5f to your computer and use it in GitHub Desktop.
Save ahcode0919/d4a1102fc3c43273d7e6b921268a4a5f to your computer and use it in GitHub Desktop.
Example of the singleton pattern in Swift
//XCode Playground Friendly
/**
Singleton Pattern - Ensures that only one instance of a object exists in the application context
usefull for things that will have a global context across the app.
Ex: An internet connection, Credentials, etc.
* Can only be used for reference types.
*/
/*
Implementation using private initializer - This is threadsafe and the simplest implementation
*/
class Singleton {
static let sharedInstance = Singleton() //<- Singleton Instance
var instanceNum: Int = 0
private init() { /* Additional instances cannot be created */ }
}
/* Test Code */
let instance1 = Singleton.sharedInstance
let instance2 = Singleton.sharedInstance
instance1.instanceNum = 1
instance2.instanceNum = 2
assert(instance1.instanceNum == 2)
@jhoanrivers
Copy link

How if instantiation needs a parameter?

@ahcode0919
Copy link
Author

How if instantiation needs a parameter?

@jhoanrivers

Hi, there is no parameter in the initialization. The initializer is actually private.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment