属性初始化程序在“自我”可用之前运行 [英] 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.
有
具有两个简单的类,其中一个引用另一个,如下所示;
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!
推荐答案
如 vadian 所正确指出的,您应该在以下情况下创建 init
:
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.
这篇关于属性初始化程序在“自我”可用之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文