String { print("m" /> String { print("m" /> String { print("m"/>

Inconsistency in lazy variable initialization between static and instance properties in Swift

48 Views Asked by At
struct MyStruct {
    static var x = myX()
    lazy var y = myY()
}

func myX() -> String {
    print("myX is running")
    return ""
}

func myY() -> String {
    print("myY is running")
    return ""
}

MyStruct.x = "X"
var myStruct = MyStruct()
myStruct.y = "Y"

print("Done")

prints:

myX is running
Done

In other words static lazy variable gets initialized just before assigning, while instance property is just assigned.

0

There are 0 best solutions below