Singletons in Swift

Please don't start a barrage on me just because I mentioned the word singleton. There are various use cases where you might want to use. For example, in one of our apps, we maintain the current account for the app. This user is maintained as a singleton object. Even if there are multiple accounts in the system, there could only be one active account at a given time. Every time user is switched, the singleton keeps the track of a selected user.

To compare this is how we will setup,

Singleton in the Objective-C

@interface JKAccount : NSObject

@property (nonatomic, copy, readonly) NSString* accountName;

@end

@interface JKAccount ()

@property (nonatomic, copy, readwrite) NSString* accountName;

@end

@implementation JKAccount

+ (instancetype)sharedAccountManager {
    static dispatch_once_t onceToken;
    static JKAccount* account = nil;
    dispatch_once(&onceToken, ^{
        account = [[JKAccount alloc] init];
    });
    return account;
}

- (instancetype)init {
    self = [super init];
    if (!self) { return nil; }
    
    _accountName = @"Default Account";
    return self;
}

@end

Singleton in Swift

class JKAccount {
    static let sharedAccount = JKAccount()
    let accountName: String
    private init() {
        accountName = "Default Account"
    }
}

Hope the chances are less that you will ever have to use singleton in your app. But if you ever have to, hope this post will help you to make that addition. You must have noticed how concise it is to declare a singleton in Swift as compared to Objective-C