1

I'm trying to create int object variable in singleton class. This my ObjC version:

+(MyClass*) single
{
    static MyClass *shareObject = nil;
    static dispatch_once_t onceToken;
    dispatch_once ( &onceToken, ^{
        shareObject = [[self alloc] init];
        shareObject.myArray = [NSMutableArray new];
    });
    return shareObject;
}

Swift version:

class MyClass {

    static let sharedInstance = MyClass()
    var myArray = Array<Any>()
}

In case of the ObjC version I know myArray is init once. But my question to you guys in case of the Swift version. Does the myArray variable would be init once?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2924482
  • 8,380
  • 23
  • 89
  • 173
  • You may be interested to know that the accessor for a `static` (or global) stored variable actually currently uses `dispatch_once` under the hood on Apple platforms (compare http://stackoverflow.com/q/43374222/2976878) – making it more or less the direct equivalent of your Obj-C `+single` method. – Hamish May 19 '17 at 18:39

1 Answers1

1

You need to add a private initializer to make sure nobody else can manually instantiate MyClass.

class MyClass {
    static let sharedInstance = MyClass()

    var myArray = Array<Any>()

    private init() {}
}

This way there can only ever be one object of MyClass (the singleton), thus the initializers (= Array<Any>()) will only run once. And all this is thread safe.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • If I use the private init(). I'm getting initializer is inaccesible due to private protection. In the ObjC sample shareObject.myArray = [NSMutableArray new]; The array can be use on any class use by the singleton keeping the content – user2924482 May 19 '17 at 17:37
  • "I'm getting initializer is inaccesible due to private protection" That's the WHOLE point of a singleton. You want a single instance of an object, (`sharedInstance` as you named it), and no more. – Alexander May 19 '17 at 17:47
  • You have to access the attributes of your singleton class using MyClass.sharedInstance.myArray.. You can't create an object of myclass .. You are trying to get its instance that's why it's giving an error – Hobbit May 19 '17 at 18:23
  • @UmerFarooq this is what I was looking for. I really appreciated – user2924482 May 19 '17 at 18:32