Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property initializers run before 'self' is available

Seems like I'm having a problem with something that shouldn't be the case... But I would like to ask for some help.

There are some explanations here on the Stack I don't get.

Having two simple classes where one refers to another, as per 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 the commented compile error. May someone please tell me what should I do to solve the case?

like image 294
RafalK Avatar asked Apr 21 '17 19:04

RafalK


People also ask

What is a property initializer?

The new class “property initializers” allows you to define methods (or any property) in your React components using regular ES6 classes without worrying about binding.

What is a property initializer Swift?

Swift provides a default initializer for any structure or class that provides default values for all of its properties and doesn't provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.

What is INIT in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.


2 Answers

As correctly pointed out by vadian you should create an init in such scenarios:

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

You can't provide a default value for a stored property that depends on another instance property.

like image 143
Paulo Mattos Avatar answered Sep 28 '22 12:09

Paulo Mattos


You should declare life like this:

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

Because you are trying to initialise one property(variable) with another during initialisation process. At this time variables are not available yet.

like image 37
Eugene Laminskiy Avatar answered Sep 28 '22 11:09

Eugene Laminskiy