Swift implements Singleton mode
The singleton pattern is implemented in every language, and the swift language has been available for a few days. Look at the document through these days. We have written a single example of Swift, for everyone to learn to communicate, please correct me.
---if reproduced please specify the source, I GitHub blog new address-Yueruo ' s Blog-http://yueruo.github.io---
Because Swift language weakens the boundary between struct and class, here I give my own two kinds of single-instance implementations
Class version number:
class SwiftSingleton{ class func shareInstance()->SwiftSingleton{ struct YRSingleton{ static var predicate:dispatch_once_t = 0 static var instance:SwiftSingleton?
= nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=SwiftSingleton() } ) return YRSingleton.instance! }}
For singleton classes. Requires a unique shareinstance method for the external output instance. And through the official documentation of the search, found that for class. Static methods can be used class func
to mark. Static variables are used for class var
processing, but here I use the static variables of the internal struct to store the unique instance.
Called, you can use the
var swiftInstance1=SwiftSingleton.shareInstance()var swiftInstance2=SwiftSingleton.shareInstance()if swiftInstance1===swiftInstance2{//“===”判别是否是同一个实例对象 println("they are the same instance!")}
In addition, the above uses the Dispatch_once, has had the GCD programming experience to be familiar, can guarantee the thread security, and only then will be called once.
struct version number
The struct version number is almost identical to the class version number, the only difference being that the keyword used by func is class func
changed tostatic func
struct StructSingleton{ static func shareInstance()->StructSingleton{ struct YRSingleton{ static var predicate:dispatch_once_t = 0 static var instance:StructSingleton?
= nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=StructSingleton() } ) return YRSingleton.instance! }}
Swift Language Implementation Singleton mode