0

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.

Nata Mio
  • 2,168
  • 3
  • 22
  • 46
  • 3
    It is far easier in Swift, have a look at http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift. – Martin R Dec 28 '15 at 08:12
  • @MartinR , if I've defined `class Helper { static let sharedInstance: Helper = Helper() private init() { print("AAA"); } }` then how do i use it in other classes ? i need to do like `let x = Helper. sharedInstance` ? – Nata Mio Dec 28 '15 at 08:43
  • Where is the problem? That should work (if you remove the space character in `Helper. sharedInstance`). – Martin R Dec 28 '15 at 10:35

2 Answers2

4

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()
Erez Hod
  • 1,813
  • 2
  • 23
  • 47
  • 1
    This does not compile and does not implement a "shared instance" because you forgot to make the property static. Correct implementations can be found here: http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift. – Martin R Dec 28 '15 at 10:33
  • 1
    You should make the `default init private`. Please add this code `private init() {}` – Luca Angeletti Dec 28 '15 at 12:05
0

It's this simple:

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

class Helper {

}
Marius Fanu
  • 6,589
  • 1
  • 17
  • 19
  • 1
    This is not a Singleton Class – Luca Angeletti Dec 28 '15 at 12:03
  • @appzYourLife there's no such thing as a `Singleton Class`. Singleton is a design pattern, and you can implement it in multiple ways, either like I did it or like the other people suggested via a `static` variable on a `class`. – Marius Fanu Dec 28 '15 at 12:13
  • @appzYourLife , Then is it possible for you to translate my objective-c code into swift for singleton class ? Swift way is complicated to implement. – Nata Mio Dec 28 '15 at 12:42
  • @MariusFanu: `[...] The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object.` [Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern). I can't see such a mechanism provided by your code. It's up to the developer using the global constant and avoiding the initialization of a new `Helper`. So I don't think your code is a valid implementation of the Singleton Design Pattern. – Luca Angeletti Dec 28 '15 at 12:52
  • @appzYourLife That's just one way to implement it. If you scroll down, on that same wiki page, you'll see `The enum way`, which is not a class. A `Singleton`, must be `accessible` and `point to that same instance`, both things my example does. – Marius Fanu Dec 28 '15 at 13:01
  • @MariusFanu: I see your point. But I still don't think that simply declaring a global constant referencing the instance of a class does mean implementing the Singleton Design Pattern. – Luca Angeletti Dec 28 '15 at 13:07
  • The annoying part is each time i need to access foo() for example i have to go throw : Helper.sharedInstance. foo() instead of just helper.foo() ? any suggestion to utilize it ?@appzYourLife – Nata Mio Dec 28 '15 at 13:14
  • @NataMio: look [here](http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift) at the **Class Constant** section. – Luca Angeletti Dec 28 '15 at 13:16
  • I have to do like : `Singleton. sharedInstance.fooexample()` which is very long each time i want to access `fooexample()`. is possible to do like `sharedInstance.fooexample()` or `Singleton.fooexample()` ? – Nata Mio Dec 28 '15 at 13:25