Reputation:
I am learning about Singleton pattern in swift and efficient way to create a Singleton class and found out the best way to create as below.
class SingletonClass{
static let sharedInstance = SingletonClass()
}
Since i have use the let
statement it is read only property and has to be thread safe so there is no need of dispatch_once() as of Objective C.And static
is used to make the sharedInstance
variable as a class
variable i guess.
But how does this guarantee there is only one instance created throughout the application?is there a small thing i am missing?
Upvotes: 19
Views: 20601
Reputation: 18181
If you want to prevent instantiation of your class (effectively restricting usage to only the singleton), then you mark your initializer as private
:
class SingletonClass {
static let shared = SingletonClass()
private init() {
// initializer code here
}
}
Upvotes: 25
Reputation: 10839
Make private init, for example :
final class Singleton {
// Can't init is singleton
private init() { }
//MARK: Shared Instance
static let sharedInstance: Singleton = Singleton()
//MARK: Local Variable
var emptyStringArray : [String] = []
}
Upvotes: 5
Reputation: 48085
You're right. And you may want to read Files and Initialization about how global and static variable are handle in Swift
Swift use this approach
Initialize lazily, run the initializer for a global the first time it is referenced, similar to Java.
It says
it allows custom initializers, startup time in Swift scales cleanly with no global initializers to slow it down, and the order of execution is completely predictable.
The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as
dispatch_once
to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.
Upvotes: 1
Reputation: 369
What guarantees it is only created once is the keyword static. you can reference this article: https://thatthinginswift.com/singletons/
Hope that helps.
The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs. In simple terms, it means that you can call a method, even if you've never created the object to which it belongs
Upvotes: 10