Swift World: Design Patterns — Singleton

Peng
SwiftWorld
Published in
1 min readMar 9, 2017

--

Singleton is very popular in Cocoa. We can find different use cases. The following are two examples.

let default = NotificationCenter.defaultlet standard = UserDefaults.standard

We will not talk about what singleton is and its advantages. You can find so many resources on the Internet. We want to focus on how to write our own.

Do you remember how to do this in the Objective-C world? Here is a template which maybe you’ve ever seen. The sharedInstance = [[Car alloc] init]; will only executed once. This is guaranteed by dispatch_once.

@interface Car : NSObject
@end
@implementation car+ (instancetype)sharedInstance {
static Car *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Car alloc] init];
});
return sharedInstance;
}
@end

What about Swift?

class Car {
static let sharedInstance = Car()
}

or a little complex

class Car {
static let sharedInstance: Car = {
let instance = Car()
return instance
}()
}

Really? It’s so simple. Then where is dispatch_once? How do you guarantee the codes only run once? The secret is the ‘static’ keywords. The static property will be lazily initialized once and only once.

Thanks for your time. Please clap to get this article seen by more people. Please follow me by clicking Follow. As a passionate iOS developer, blogger and open source contributor, I’m also active on Twitter and GitHub.

--

--

Peng
SwiftWorld

Engineers are the artists of our generation.