MVCS pattern with Swift (Code Samples)


#1

Hi there,

          was wondering if the authors have any comments on how to create the thread safe Singleton Shared Store class in Swift? I seem to find the following source code. 

Credits: Martin (http://code.martinrue.com/posts/the-singleton-pattern-in-swift)
dispatch_once

[code]class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var instance: Singleton?
static var token: dispatch_once_t = 0
}

dispatch_once(&Static.token) {
  Static.instance = Singleton()
}

return Static.instance!

}
}[/code]

This seems to be similar to the pattern as stated by the book which uses dispatch_once. However, there are also another variations such as using a Global constant or a Nested Struct. “let” is also thread safe since it defines a constant.

Credits hpique http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift

Global Constant Approach

[code]
private let _SingletonSharedInstance = Singleton()

class Singleton {
class var sharedInstance : Singleton {
return _SingletonSharedInstance
}
}[/code]

Nested struct

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

Just curious, is there a recommended approach to adopting the MVCS pattern for the purpose of replicating the Book’s examples in Swift?