Singleton in Swift

单例模式是我们常用的一种设计模式,在Swift中如何使用呢?

  • 先回顾下在Objective-c中的使用
+ (instancetype)sharedInstance {
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
 
    return _sharedInstance;
}
  • Swift 中 苹果推荐使用方式是简单地使用一个静态类型属性,它保证只会初始化一次而且是懒加载的,即使在多个线程同时访问时也是这样。
class Singleton {
    static let sharedInstance = Singleton()
}
  • 如果你需要在初始化时做一些特别的设置,可以这样
class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

你可能感兴趣的:(Singleton in Swift)