SwiftSingleton


tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions.

An exploration of the Singleton pattern in Swift. All approaches below support lazy initialization and thread safety.

Issues and pull requests welcome.

Approach A: Class constant

class SingletonA {

    static let sharedInstance = SingletonA()

    init() {
        println("AAA");
    }

}

This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let.

Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.

Approach B: Nested struct

class SingletonB {

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

}

Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.

Approach C: dispatch_once

The traditional Objective-C approach ported to Swift.

class SingletonC {

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

I'm fairly certain there's no advantage over the nested struct approach but I'm including it anyway as I find the differences in syntax interesting.

SwiftSingleton(原文)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 恼人的秋风来势汹汹。她跟儿子先后得了重感冒,所幸老公跟一周岁多的小妞儿安然无恙。 儿子高烧不退,刚开始都两天没敢去...
    梅庄主在梅庄阅读 3,375评论 0 3
  • 永远的好朋友。她们相信这份誓言能坚守到永远,她们会一起变老,坐在老旧露台的两张摇椅上,回顾往事一起欢笑。——《萤火...
    Baron_0201阅读 3,437评论 3 1
  • 1. 模仿湖南儿歌《月亮粑粑》写一段荒诞不经然而押韵的文字(不用一韵到底,可以几句一变化): 小姑娘, 想阿娘(南...
    mayan2017阅读 2,767评论 2 2