Singleton is a popular design pattern and widely used in Cocoa/Cocoa Touch. We may want to use singleton if it should be accessed everywhere in the app, or there must be one and only one instance in the entire life cycle. The best creation and access of singleton would be using a dispatch_once_t token like this:

@implementation MyManager
+ (id)sharedManager {
    static MyManager *staticInstance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        staticInstance = [[self alloc] init];
    });
    return staticInstance;
}
@end

dispatch_once_t ensures the code in the block will be only called once, without any concern about threads. It is a thread-safe way to create and use singleton.

Since GCD can be use seamless in Swift, so we can write a similar version for it:

class MyManager {
    class var sharedManager : MyManager {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var staticInstance : MyManager? = nil
        }

        dispatch_once(&Static.onceToken) {
            Static.staticInstance = MyManager()
        }

        return Static.staticInstance!
    }
}

There is no stored property (class var) in Swift now, so we have to use a struct to hold these variables. It makes the code longer and not so cool.

Although there should be a big issue in the code above, we have an easier way to ensure the thread safety in Swift. By using let and constant, the code above could be modified to:

class MyManager {
    class var sharedManager : MyManager {
        struct Static {
            static let sharedInstance : MyManager = MyManager()
        }

        return Static.sharedInstance
    }
}

There is even another way to write a singleton in Swift, and it is recognized as the best way for now. We can use a computed class property and provide a pre-stored value. Fortunately, we now have private keyword to limit the access protection level. So just use a private let to save an instance, and return it in the class property will produce a simple singleton, without nesting or dispatching:

private let sharedInstance = MyManager()

class MyManager  {
    class var sharedManager : MyManager {
        return sharedInstance
    }
}

If there is no special demand, I suggest using this kind of code to implement a singleton.

Improvement in Swift 1.2

In Swift 1.1 and previous, stored property like static let or staic var was not supported. However, it was added from Swift 1.2. Currently we can put sharedInstance into the class scope instead. It could make more sense that the instance is belonging to the class.

In Swift 1.2 and later, a recommended way to write a singleton would be like this:

class MyManager  {
    private static let sharedInstance = MyManager()
    class var sharedManager : MyManager {
        return sharedInstance
    }
}