I realize that static
variables are implicitly lazy
, which is really great. Doing the below will not create the instance until it's first called:
static var test = Test()
However, assigning a new instance to the static
variable initializes the original, then assigns the new instance which is troubling for me:
SomeType.test = AnotherTest() //Initializes Test then AnotherTest type
To give more context on what I'm trying to do, I'm trying to setup a pure Swift dependency injection using this article. It's not working so well when swapping the types out in my unit tests because the original type always gets initialized when assigning the mock type.
Here's a more fuller, playground sample:
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 make MyMap.prop1 = MyMock()
not first initialize the original MyClass
first?