swift单例

SwiftSingleton

tl;dr: Use theclass constantapproach if you are using Swift 1.2 or above and thenested structapproach 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 oflet.(上述代表也实现了延迟加载技术)

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 { 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 { var sharedInstance: SingletonC { var oncetoken: dispatch_once_t = 0 var instance: SingletonC? = nil } dispatch_once(&Static.oncetoken) { Static.instance = SingletonC() } .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.(使用GCD技术实现的单例模式)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...