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;
}
0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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/

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.