Last active
March 3, 2021 06:44
-
-
Save ahcode0919/d4a1102fc3c43273d7e6b921268a4a5f to your computer and use it in GitHub Desktop.
Example of the singleton pattern in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) |
How if instantiation needs a parameter?
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
How if instantiation needs a parameter?