2

I've made a small class to test when object declaration occurs.

class MyObject
{
    static let instance = MyObject();

    required init()
    {
        println("init")
    }
}

And when I run this, "init" is only printed when I reference MyObject.instance, meaning that static variables are declared lazily.

The reason I need this to be eager is because I want to keep a lookup table of object instances for myself (with weak references, don't worry). Instances to be inserted during their init and expose a lookup function, so the functionality is encapsulated.

I'd prefer if I didn't need a separate function at App start to make references to static variables to achieve this.

I am not aware of an eager keyword, but is there an accepted solution to this? Will it be added in Xcode 7?

Kevin
  • 1,626
  • 16
  • 30
  • 1
    In very early versions of Swift you could override the `load` method, but that feature was removed in Swift 1.2, compare http://stackoverflow.com/questions/24898453/swift-objective-c-load-class-method or http://stackoverflow.com/questions/28422468/method-load-defines-objective-c-class-method-load-which-is-not-permitted-by. It seems that there is no mechanism to execute class methods at program start automatically. – Martin R Sep 16 '15 at 08:58
  • I'm a bit disappointed that they force default behaviour without an off switch. But thanks for checking. Load would've been the best but I think I'll settle for `didFinishLaunchingWithOptions` – Kevin Sep 16 '15 at 09:19
  • I'd wager the reason for the removal of this is (probably not limited to) the fact that it becomes very difficult, if not impossible, to reason about the order of execution. This way you know exactly when you first call MyObject.instance relative to other code in your project. – Steve Wilford Sep 16 '15 at 10:05
  • So I can't take sharp corners because of the training wheels :( – Kevin Sep 16 '15 at 10:12

0 Answers0