Property initializers run before 'self' is available

懵懂的女人 提交于 2019-12-01 15:44:45

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.

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.

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