2

In Apple's new Swift programming language, I came across the following:

"Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state."

Is the above rule valid even for @lazy Stored Properties?

3 Answers 3

2

No you do not:

A lazy stored property is a property whose initial value is not calculated until the first time it is used...

You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes...

Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.

Source

Basically meaning that it does not have a value and does not need one immediately after initialization.

Sign up to request clarification or add additional context in comments.

2 Comments

So a lazy stored property can be left in an intermediate state?
@DebaprioB Sort of. Yes, in the sense that they do not need a state after initialization. No, in the sense that they must provide one the first time they are accessed.
2

Lazy properties must have an initializer.

enter image description here

However, by marking them @lazy, the value of the initializer is computed only when needed.

class DataImporter{}

class DataManager {
    @lazy var importer:DataImporter = DataImporter()
}

var dm = DataManager()

// do stuff with dm and other lines of code

// later if you reference dm.importer
dm.importer // <-- at this moment the call to DataImporter is made

Comments

1

Think of it this way: lazy stored properties do have an initial value, it is just not yet calculated.

The rule you describe means that the object has to determine the initial value itself, it cannot be specified after init returns, e.g. by a factory. This is true for lazy stored properties, as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.