https://github.com/hpique/SwiftSingletongit
https://developer.apple.com/swift/blog/?id=7github
how should global variables work?express
The first approach was ruled out because Swift doesn’t need constant expressions like C does. In Swift, constants are generally implemented as (inlined) function calls. And there are good reasons to use complex initializers, e.g. to set up singletons or allocate a dictionary.swift
The second approach was ruled out because it is bad for the performance of large systems, as all of the initializers in all the files must run before the application starts up. This is also unpredictable, as the order of initialization in different files is unspecified.app
Swift uses the third approach, which is the best of all worlds: it allows custom initializers, startup time in Swift scales cleanly with no global initializers to slow it down, and the order of execution is completely predictable.atom
The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.spa
支持Swift1.2以上的版本code
public class SingletonA { static let sharedInstance = SingletonA() private init() { print("init") } public func speak() -> String { return "hello!" } } print(SingletonA.sharedInstance.speak())
支持Swift全部版本orm
public class SingletonA { class var sharedInstance: SingletonA { struct Static { static let instance: SingletonA = SingletonA() } return Static.instance } private init() { print("init") } public func speak() -> String { return "hello!" } }
public class SingletonA { class var sharedInstance: SingletonA { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: SingletonA? = nil } dispatch_once(&Static.onceToken) { () -> Void in Static.instance = SingletonA() } return Static.instance! } private init() { print("init") } public func speak() -> String { return "hello!" } }
private let instance = SingletonA() public class SingletonA { class var sharedInstance: SingletonA { return instance; } private init() { print("init") } public func speak() -> String { return "hello!" } }