[英]Why do will/didSet trigger initializer error, but not regular set/get?
這樣可以編譯:
class Foo {
var number = 0
var name: String
init(name: String){ self.name = name }
}
class SubFoo: Foo {
init(_ x: Int){
super.init(name: "abc")
}
var a: Int {
set {}
get {
return 0
}
}
}
a
是計算的屬性,因此不需要初始化。
但這不能編譯:
class SubFoo: Foo {
init(_ x: Int){
super.init(name: "abc")
}
var a: Int {
willSet {}
didSet {
print(oldValue)
}
}
}
SubFoo的init方法顯示如下:
錯誤:未在super.init調用super.init(name:“ sdf”)初始化的屬性'self.a'
a
仍然不是“真實”屬性,那么編譯器在這里到底期望什么?
奇怪的是,我可以通過執行以下操作使錯誤靜音:
init(_ x: Int){
a=0
super.init(name: "sdf")
}
為什么willSet
要求a=0
而不是正常set
?
雖然willSet
和didSet
出現在屬性后的方括號中,但類似於計算方法get
和set
,它們不是指計算屬性的行為。 willSet
和didSet
作用於存儲的屬性。 這也是為什么您可以為它們提供默認值,但不能為get/set
提供默認值的原因:
var a: Int = 6 { // this line would not compile for a computed property
willSet {
}
didSet {
print(oldValue)
}
}
這就是init
編譯器錯誤的原因-沒有初始化存儲的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.