初始化发生在哪里,是在 init 方法中还是在实例声明中?
Where is initialization taking place, in the init method or in the instance declaration?
请不要叫我去苹果官网上看一篇link,因为我都看了!
我对 属性 'text' 的实际初始化发生在哪里感到困惑?它是在 init 方法中还是在实例声明中发生?
因为在我看来,文本 属性 的初始化发生在实例声明中,它被赋予值 "How about beets?"
如果是这样,那为什么 apple book 声明必须在创建实例之前初始化所有属性?在 class 定义中(如果我错了请纠正我)
最后,如果 'text' 实际上在 class 定义中被初始化....初始化在哪里??
class SurveyQuestion {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
初始化发生在 init
方法中。请注意,init
接受一个参数,text
,并将该参数分配给 self.text
。
我相信您的代码遵循的过程是:
- 您调用
SurveyQuestion(text: "How about beets?")
以获取 SurveyQuestion class 的实例。
- 当 class 为 运行 时,它的初始化方法
init(text: String)
会初始化所有属性。这意味着您正在初始化文本 属性,并为其赋值。
- 最后 class 完成初始化,您将获得 class 的一个实例。
这与 Apple 的文档相对应,因为当您初始化 class 时,属性会被初始化,但是在 init 方法完成之前您不会获得 class 实例,这意味着直到所有属性已初始化。
抱歉初始化冗余,我没有找到另一种解释方式。
希望能解决你的疑惑。
请不要叫我去苹果官网上看一篇link,因为我都看了!
我对 属性 'text' 的实际初始化发生在哪里感到困惑?它是在 init 方法中还是在实例声明中发生?
因为在我看来,文本 属性 的初始化发生在实例声明中,它被赋予值 "How about beets?"
如果是这样,那为什么 apple book 声明必须在创建实例之前初始化所有属性?在 class 定义中(如果我错了请纠正我)
最后,如果 'text' 实际上在 class 定义中被初始化....初始化在哪里??
class SurveyQuestion {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
初始化发生在 init
方法中。请注意,init
接受一个参数,text
,并将该参数分配给 self.text
。
我相信您的代码遵循的过程是:
- 您调用
SurveyQuestion(text: "How about beets?")
以获取 SurveyQuestion class 的实例。 - 当 class 为 运行 时,它的初始化方法
init(text: String)
会初始化所有属性。这意味着您正在初始化文本 属性,并为其赋值。 - 最后 class 完成初始化,您将获得 class 的一个实例。
这与 Apple 的文档相对应,因为当您初始化 class 时,属性会被初始化,但是在 init 方法完成之前您不会获得 class 实例,这意味着直到所有属性已初始化。
抱歉初始化冗余,我没有找到另一种解释方式。 希望能解决你的疑惑。