Before you write Swift's Singleton method, you can review the objective-c of the single example:
1 + (Instancetype) sharedsingleton{ 2 static id instance; 3 Static dispatch_once_t Oncetoken; 5 dispatch_once (&oncetoken, ^{ Span style= "color: #008080;" >6 instance = [[Self alloc] init]; 7 }); 8 return instance; 9 }
The first thing to consider is to follow the notation in OC to write one.
So one way to do this in Swift is as follows:
1 classSingleton:nsobject {2 3 Staticvar Instance:singleton?4 Staticvar oncetoken:dispatch_once_t =05 6 //Follow the notation in OC7 classFunc Sharedsingleton ()Singleton {8Dispatch_once_ (&oncetoken) {() Voidinch9Instance =Singleton ()Ten One } A returninstance! - } -}
Swift has done a lot of optimization on the OC Foundation, so consider using some of the new features of Swift to implement the singleton.
Given that the let in Swift itself is thread-safe, implementing a singleton in Swift can be very concise:
static Let Sharedsingleton = Singleton ()
Since the implementation has changed from the original function to a property, so the use of the corresponding adjustments need to be made, when used as follows:
Singleton.sharedsingleton
Thus, Swift, which has been optimized to absorb the advantages of multiple languages, has been largely streamlined compared to the previous one.
Implementing a singleton approach in Swift