Created
March 1, 2016 05:39
-
-
Save getmetorajesh/7f565fd99a9f5ce47843 to your computer and use it in GitHub Desktop.
Single line singleton swift
This file contains hidden or 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
| // single line Singletons | |
| /* | |
| DA RULES OF DA SINGLETON, MAHN | |
| There are essentially three things to remember about the Singleton: | |
| A singleton has to be unique. This is why it's called a singleton. There can only be one instance for the lifetime of the application it exists in. Singletons exist to give us singular global state. Such examples are NSNotificationCenter, UIApplication, and NSUserDefaults. | |
| To maintain a singleton's unique-ness, the initializer of a singleton needs to be private. This helps to prevent other objects from creating instances of your singeton class themselves. Thank you to all who pointed that out to me :) | |
| Because of rule #1, in order to have only one instance throughout the lifetime of the application, that means it needs to be thread-safe. Concurrency really sucks when you think about it, but simply put, if a singleton is built incorrectly in code, you can have two threads try to initialize a singleton at the same time which can potentially give you two separate instances of a singleton. This means that it's possible for it to not be unique unless we make it thread-safe. This means we want to wrap the initialization in a dispatch_once GCD block to make sure the initialization code only runs once at runtime. | |
| Being unique and initializing in one place in an app is easy. The important thing to remember for the rest of this post is that a singleton fulfill the much-harder-to-see dispatch_once rule. | |
| */ | |
| class OnlyOneSingleton { | |
| static let sharedInstance = OnlyOneSingleton() | |
| private init() {} //This prevents others from using the default '()' initializer for this class. | |
| func printSomething() { | |
| print("dsad") | |
| } | |
| } | |
| OnlyOneSingleton.sharedInstance.printSomething() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment