Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift static property initilizers are lazy why I could declared it as a constant

As far as I known (see reference A), Static property initilizers are lazy, and I found the following description by the office documents

You must always declare a lazy property as a variable (with the var keyword) because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

From the above information, I think I couldn't define the static property as a constant variable and I made a tryout, it turns out I can do that without triggering any error from the compiler.

Example:

class Person {
    static let firstNaID = "First Name"
    static let lastNaID = "Last Name"
}

Question: Is this a bug of the Swift 3.0.1 or I was wrong.

Reference A: Neuburg. M.2016. IOS 10 Programming Fundamental with Swift. P127

Thanks for your time and help

like image 855
SLN Avatar asked Oct 17 '25 14:10

SLN


2 Answers

Neuburg M. is drawing a distinction between static properties and instance properties. You are pretending to ignore that distinction. But you cannot ignore it; they are totally different things, used for different purposes.

In this code:

class Person { // let's declare a static property
    static let firstNaID = "First Name"
}

... firstNaID is already lazy. But now try to do this:

class Person { // let's declare an instance property
    lazy let firstNaID : String = "First Name" // error
}

You can't; as things stand (up thru Swift 3.1), you have to say lazy var instead — and when you do, you get a lazy instance property.

Your static let declaration thus doesn't accomplish what lazy let wanted to accomplish, because a static property is not an instance property.

like image 188
matt Avatar answered Oct 20 '25 13:10

matt


You are talking about type properties

Form the same chapter of the documentation

Type Properties

... Type properties are useful for defining values that are universal to all instances of a particular type, such as a constant property that all instances can use ...

Stored type properties can be variables or constants. Computed type properties are always declared as variable properties, in the same way as computed instance properties.

NOTE

...

Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.

like image 26
vadian Avatar answered Oct 20 '25 13:10

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!