保證一個類公有一個實例。並提供一個訪問它的全局訪問點。javascript
一、使用場景java
單例的建立有很是多寫法,Swift支持僅僅有struct支持靜態變量。class不支持靜態變量。因此很是easy想到,在類的內部使用struct就能解決引用的保存問題,代碼例如如下:swift
class SwiftSingleton { class var shared: SwiftSingleton { dispatch_once(&Inner.token) { Inner.instance = SwiftSingleton() } return Inner.instance! } struct Inner { static var instance: SwiftSingleton? static var token: dispatch_once_t = 0 } }
class SwiftSingletonTest: XCTestCase { func testSingleton() { let singleton1 = SwiftSingleton.shared let singleton2 = SwiftSingleton.shared assert(singleton1 === singleton2, "pass") } }
class SwiftSingleton { class var shared: SwiftSingleton { return Inner.instance } struct Inner { static let instance = SwiftSingleton() } }
struct SwiftSingleton { var name: String = "1" static let shared = SwiftSingleton() } var single1 = SwiftSingleton.shared var single2 = SwiftSingleton.shared single2.name = "2" println("------->\(single1.name)") println("------->\(single2.name)")
------->1 ------->2 Program ended with exit code: 0
版權聲明:本文博客原創文章。博客,未經贊成,不得轉載。優化