在做开发的时候,经常会用到单利设计模式,在swift开发中单利有两种写法:一种是按照OC的思维方式的写法,另外一种是纯swift的写法
oc思路 写法
static var onceToken: dispatch_once_t = 0
static var instance: NetworkTools?
class func shareNetworkTools() -> NetworkTools
{
dispatch_once(&onceToken) { () -> Void in
print("我被调用了")
instance = NetworkTools()
}
return instance!
}
swift 写法
static let instance: NetworkTools = NetworkTools()
class func shareNetworkTools() -> NetworkTools
{
return instance
}
* let 本身就只会被创建一次
* let 是线程安全的