Ali
Ali

Reputation: 515

Initialization of properties in a class, lazy properties in specific?

  1. In swift, are properties in a class initialized when I declare an instance of that class?

  2. Lazy properties aren't initialized until they are called/used (correct me if I'm wrong) , so basically declaring an instance of a class will not initialize lazy properties but WILL initialize regular properties if there are any (called stored, I believe) ?

  3. lastly, the book says that the instance below is "declared" AND "initialized".......I can see that it IS declared but how is it being "initialized"?? There is not argument being sent in-between the parentheses??

    let someClass = SomeClassWithLazyVar()
    

Upvotes: 1

Views: 228

Answers (2)

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

  1. Yep, that is correct.
  2. Yep, that is also correct.
  3. What is being initialized is the constant someClass. Declaration is the introduction of a new named value into your program. You declare the name of the constant (or variable) and identify its type like this:

    let someClass: SomeClassWithLazyVar

But at that point it still hasn't been initialized. You initialize the constant by assigning it a value:

someClass = SomeClassWithLazyVar()

The vast majority of the time (especially with constants) you declare the constant and initialize it at the same time:

let someClass = SomeClassWithLazyVar()

Whether or not you need to pass arguments inside the parentheses depends on the initializer for the object that you are creating. I'm assuming that SomeClassWithLazyVar has an initializer that takes no arguments, like this:

init() { }

Upvotes: 2

MustangXY
MustangXY

Reputation: 358

  1. Yes (only "regular" stored properties - this doesn't apply to computed properties and lazy properties). Even default values are assigned only when an actual instance of the class is created.

  2. Yes. Apple Documentations says:

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

  1. What you pasted is a "constructor call". When you write name_of_class() you're actually creating an instance of the class (and calling its init() method immediately after). Therefore someClass is being initialised with said instance.

Upvotes: 1

Related Questions