您的位置:首页 > 移动开发 > Swift

【Swfit】Swift与OC两种语法写单例的区别

2015-05-23 00:04 561 查看
Swift与OC两种语法写单例的区别

例如写一个NetworkTools的单例

(1)OC写单例

+ (instancetype)sharedNetworkTools {
static id instance;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
//这里可以做一些初始化
});

return instance;
}


(2)Swift写单例

// 定义一个私有的静态成员
// `let` 就是线程安全的
// 这句代码懒加载的,在第一次调用的时候,才会运行
private static let instance = NetworkTools()

class func sharedNetworkTools() -> NetworkTools {
return instance
}


假如要预先初始化一些属性,则可以这么写

private static let instance : NetworkTools = {
let netWorkTool = NetworkTools()
//这里初始化属性

return netWorkTool
}()

class func sharedNetworkTools() -> NetworkTools {
return instance
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: