Property initializers start before "self".

It seems like I have a problem with something that should not be so ... But I would like to ask for help.

There are a few explanations here on the stack that I am not getting.

Having two simple classes where one refers to the other as shown below:

class User { lazy var name: String = "" lazy var age: Int = 0 init (name: String, age: Int) { self.name = name self.age = age } } class MyOwn { let myUser: User = User(name: "John", age: 100) var life = myUser.age //Cannot use instance member 'myUser' within property initializer //property initializers run before 'self' is available } 

I get a commented out compilation error. Can someone please tell me what should I do to resolve this matter?

Many thanks to any good person for their help!

+5
source share
2 answers

As vadian is correctly pointed out , you must create init in such scripts:

 class MyOwn { let myUser: User var life: Int init() { self.myUser = User(name: "John", age: 100) self.life = myUser.age } } 

You cannot provide a default value for a stored property that depends on another property of the instance.

+5
source

You must declare such a life:

 lazy var life:Int = { return self.myUser.age }() 

Because you are trying to initialize one property (variable) with another during the initialization process. Variables are not yet available at this time.

+3
source

Source: https://habr.com/ru/post/1267035/


All Articles