MVCS pattern with Swift (Code Samples)


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 (

[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!


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

Global Constant Approach

private let _SingletonSharedInstance = Singleton()

class Singleton {
class var sharedInstance : Singleton {
return _SingletonSharedInstance

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?