Property initializers run before 'self' is available

最后都变了- 提交于 2019-12-01 13:49:57

问题


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?

Many thanks to any good man for help!


回答1:


As correctly pointed 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 depend on another instance property.




回答2:


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.



来源:https://stackoverflow.com/questions/43550813/property-initializers-run-before-self-is-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!