Swift VIII

I have to admit that the static variables we have in the C world (C/Cpp/ObjC) are pretty cool (Note, it’s not thread safe. This is just an example):

- (void)someMethod {
    static id variable = nil;
    if (!variable) {
        // initialize variable

What about our new favorite language, namely Swift? There is a way to achieve such awesomeness, with a little bit more code, however its more structured:

class var sharedManager: AppManager {
    struct Constants {
        static let instance = AppManager()

    return Constants.instance

In the snippet above, I’m creating a singleton accessor, with a lazy initializer, as a class property. We can now even skip the brackets when accessing the shared instance:

// Somewhere in your code