工作生活

Swift 单例

2019-07-02  本文已影响0人  雾霾下的天空

swift 官方文档

您使用单例来提供类的全局可访问的共享实例。您可以创建自己的单例,作为一种方式,为跨应用程序共享的资源或服务提供统一的接入点,比如播放声音效果的音频通道或发出HTTP请求的网络管理器。
You use singletons to provide a globally accessible, shared instance of a class. You can create your own singletons as a way to provide a unified access point to a resource or service that’s shared across an app, like an audio channel to play sound effects or a network manager to make HTTP requests.

创建单例

你使用静态类型属性创建简单的单例对象,它保证只被惰性初始化一次,即使是在多个线程同时访问时:
You create simple singletons using a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:

class Singleton {
    static let sharedInstance = Singleton()
}

你使用静态类型属性创建简单的单例对象,它保证只被惰性初始化一次,即使是在多个线程同时访问时:
If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}
上一篇 下一篇

猜你喜欢

热点阅读