Setting the initialization of a lazy static variable first assigned?

I understand that variables are static

implicit lazy

, which is really cool. Executing below will not create an instance until it is first called:

static var test = Test()

      

However, assigning a new instance to a variable static

initializes the original and then assigns a new instance, which bothers me:

SomeType.test = AnotherTest() //Initializes Test then AnotherTest type

      

To point more to what I am trying to do, I am trying to set up pure Swift dependency injection using this article.It does not work that well when replacing types in my unit tests because the original type is always initialized when assigning a layout type.

Here is a more complete, playground:

protocol MyProtocol { }

class MyClass: MyProtocol {
    init() { print("MyClass.init") }
}

////

struct MyMap {
    static var prop1: MyProtocol = MyClass()
}

protocol MyInject {

}

extension MyInject {
    var prop1: MyProtocol { return MyMap.prop1 }
}

////

class MyMock: MyProtocol {
    init() { print("MyMock.init") }
}

// Swapping types underneath first initializes
// original type, then mock type :(
MyMap.prop1 = MyMock()

prints: MyClass.init
prints: MyMock.init

      

How can I do MyMap.prop1 = MyMock()

not initialize the original one first MyClass

?

+3


source to share


1 answer


You want lazy loading. Try the following:

struct MyMap {
    private static var _prop1: MyProtocol?
    static var prop1: MyProtocol {
        get { return _prop1 ?? MyClass() }
        set(value) { _prop1 = value }
    }
}

      



Or that:

struct MyMap {
    private static var _prop1: MyProtocol?
    static var prop1: MyProtocol {
        get {
            if _prop1 == nil {
                _prop1 = MyClass()
            }
            return _prop1!
        }
        set(value) { _prop1 = value }
    }
}

      

+2


source







All Articles