0

How would you write the following in swift?

static ClassName* singleCommon = nil;
+ (ClassName*)sharedInstance {
    @synchronized(singleCommon) {
        if(!singleCommon) singleCommon = [[ClassName alloc] init];
    }
    return singleCommon;
}

2 Answers2

1

I Usually use sharedInstance in Swift like this:

private let _sharedInstance = SomeClass()

class SomeClass: NSObject {

    class var sharedInstance: SomeClass {
        get {
            return _sharedInstance
        }
    }

}

Here is a blogpost discussing this question: http://thatthinginswift.com/singletons/

danieltmbr
  • 1,022
  • 12
  • 20
  • it is smell bad, your `_sharedInstance` is out of class and it can conflict with other implementation if they resolve do same you do here – ViTUu Apr 16 '15 at 12:43
1

A good solution is:

class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static var instance: Singleton?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = Singleton()
        }

        return Static.instance!
    }
}

Solution and explanation coming from: http://code.martinrue.com

Alex
  • 541
  • 5
  • 19