Swift property expression evaluation

Hello!
There is a statement in the documentation Declarations:

The initializer expression is optional in the context of a class or structure declaration, but required elsewhere. The type annotation is optional when the type can be inferred from the initializer expression . This expression is evaluated the first time you read the property’s value. If you overwrite the property’s initial value without reading it, this expression is evaluated before the first time you write to the property.

It's looks not correct for me, as according to this code:

class T {

    var test: Int = {
        print("in T");
        return 1
    }() {
       willSet {
           print("In willSet")
       }
       didSet {
           print("In didSet")
       }
    }

}

let variable = T() // will trigger the closure immediately, before we read/write it
print(variable.test)
variable.test = 5

Could somebody explain it?

Thanks

1 Like

The text is confusing, I agree. It’s most accurately a description of the “elsewhere” case. With a struct or class, in order to initialize the value, “you” have to set all stored properties’ initial values. But you are right that users that call an initializer (particularly a default one that isn’t even written out in source) might not consider what’s happening during initialization as what “you” do.

It’s reasonable to file a bug (IMO) against the GitHub repository for the Swift book so that the text gets clarified.

The most confusing part for me is here:

This expression is evaluated the first time you read the property’s value. If you overwrite the property’s initial value without reading it, this expression is evaluated before the first time you write to the property .

As it's not correct at all.

Well, I wouldn’t say that it’s not correct “at all.” “You” have written a call to an initializer, which has to set the initial value of all stored properties.

Got you, in this way of things it could have a value, but it's not the same terms as explained the same things in other chapters.
But it's VERY confusing.

Thank you very much, you helped me the second time.

1 Like