Nata Mio
Nata Mio

Reputation: 2228

Get singleton instance in swift

I've written a class in objective-c to get me a single instance of class called helper which helps me to do a lot of different stuff.

static Helper *objHelper = nil;

@implementation Helper

- (id)init {
    self = [super init] ;
    return self;
}

///- Return Helper Singleton Instance
+ (Helper *) getHelperInstance;
{
    @synchronized (objHelper) {
        if ( !objHelper || objHelper == NULL ) {
            objHelper = [[Helper alloc] init];
        }
        return objHelper;
    }
}

I've tried to write it in swift but i don't think i made it right:

var objHelper : Helper?


override init() {
    super.init()

}

func getHelperInstance() ->Helper{

    synchronizd(objHelper == nil) {

        if objHelper == nil {

            objHelper = Helper()
        }
    }
    return objHelper!

}

and to handle synchronized :

func synchronizd(lock: AnyObject, closure:()->()) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock);
}

When i used the objective-c class i use it in my classes as :

var objHelper = Helper()
objHelper  = Helper.getHelperInstance()

but when i wrote it in swift which i have to pass parameters :

var objHelper = Helper()
objHelper  = Helper.getHelperInstance(objHelper)()

What did i converted to swift wrong ? and why its asking for (objHelper)() where when it was in objective c code it didn't ask to do that ! i just need to make my swift code runs the same as my objective-c code.

Update: i am asking of doing the singleton on another way instead of struct or whatever.my code works fine with some edits in swift and thats what in asking for.

Upvotes: 0

Views: 2443

Answers (2)

Erez Hod
Erez Hod

Reputation: 1883

In Swift it is extremely simple, keep a shared instance constant with the class reference inside the class itself like so:

class Helper {
    static let sharedInstance = Helper()

    func someMethod() {
        print("Bla bla")
    }
}

And use its methods in different classes like so:

Helper.sharedInstance.someMethod()

Upvotes: 4

Marius Fanu
Marius Fanu

Reputation: 6669

It's this simple:

// This will be a global variable accessible from anywhere
let helperSharedInstance = Helper()

class Helper {

}

Upvotes: 0

Related Questions