Singletons in Swift

If you come from the Objective-C world, you’re probably familiar with the singleton pattern.

@implementation MyClass
+ (id)sharedInstance
    static MyClass *__instance = nil
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        __instance = [[MyClass alloc] init];
    return __instance;

Okay, here’s how you declare a singleton in Swift:

class MyClass {
    static let sharedInstance = MyClass()

And that’s it.

Thanks to Swift’s immutability (using let properties), we’re able to declare the static property on the type and have it resolve its value when the type declaration is first used.

Many say that singletons are an antipattern and should be avoided. I say that it depends. If you assess that a singleton is the right way to go to solve your current proble, go for it.

However, I should remind you that Swift is not Objective-C, and the fact that you can still use the same constructs that are used in Objective-C doesn’t mean you sould. Swift is a great language to exploit value semantics and immutability.

Esta entrada fue publicada en Swift. Enlace permanente.