第一种, 类常量Class constant,建议使用方式

  • 支持懒加载, 线程安全
class Singleton  {
   static let sharedInstance = Singleton()
}

第二种嵌套结构体变量格式

class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static let instance: Singleton = Singleton()
        }
        return Static.instance
    }
}

第三种最不建议, 但最像Oc的创建方式dispatch_once

class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: Singleton? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = Singleton()
        }
        return Static.instance!
    }
}

原文链接 https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift/24147830#24147830

相关文章:

  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
  • 2022-01-25
  • 2021-11-04
  • 2021-04-26
猜你喜欢
  • 2021-09-01
  • 2021-12-21
  • 2021-11-20
相关资源
相似解决方案