Swift-Swift的Singleton三种写法
第一种:
import Foundation class SingletonA : NSObject { static let sharedInstance: SingletonA = SingletonA() private init() { print("AAA"); } }
第二种:
import Foundation class SingletonB { class var sharedInstance: SingletonB { struct Static { static let instance: SingletonB = SingletonB() } return Static.instance } private init() { print("BBB"); } }
第三种:
import Foundation class SingletonC { class var sharedInstance: SingletonC { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: SingletonC? = nil } dispatch_once(&Static.onceToken) { Static.instance = SingletonC() } return Static.instance! } private init() { print("CCC"); } }