I have a lazy property in a struct and every time I access it, it mutates the struct.
The ideal behaviour should be first time mutation only (since that's how lazy variables behave). Is this a bug in Swift or am I doing something wrong?
I have a lazy property in a struct and every time I access it, it mutates the struct.
The ideal behaviour should be first time mutation only (since that's how lazy variables behave). Is this a bug in Swift or am I doing something wrong?
It's actually the semantic. MyStruct.myProperty
is a mutating get
due to it being lazy. So every time you access myProperty
, the compiler assumes that you're mutating self
whether you actually mutate it or not. You can try the adjustment below for the same effect:
struct MyStruct {
var myProperty: Int {
mutating get { 0 }
}
}
The interface doesn't much care if it's using lazy
or custom implementation.
I find myself avoiding lazy
more and more recently, because it makes code harder to reason about and potentially behave in surprising ways -- you can't tell when exactly the code will run from simply looking at the code.