无法为不带参数的Height类型调用初始值设定项
问题描述:
我正在使用Swift iBook进行Apple的应用程序开发,直到结构章节,特别是在属性观察部分期间,它一直非常流畅地航行。我负责检查单位转换。无法为不带参数的Height类型调用初始值设定项
struct Height {
var heightInInches: Double {
willSet(imperialConversion) {
print ("Converting to \(imperialConversion)")
}
didSet {
if (heightInInches == (heightInCentimeters * 0.393701)) {
print ("Height is \(heightInInches)")
}
}
}
var heightInCentimeters: Double {
willSet(metricConversion) {
print ("Converting to \(metricConversion)")
}
didSet {
if (heightInCentimeters == (heightInInches * 2.54)) {
print ("Height is \(heightInCentimeters)")
}
}
}
init(heightInInches: Double) {
self.heightInInches = heightInInches
self.heightInCentimeters = heightInInches*2.54
}
init(heightInCentimeters: Double) {
self.heightInCentimeters = heightInCentimeters
self.heightInInches = heightInCentimeters/2.54
}
}
let newHeight = Height()
newHeight.heightInInches = 12
从书和Swift文档,我认为这应该工作。但是,我收到一条错误消息:
“无法为不带参数的'Height'类型调用初始值设定项。
- 这是什么意思,什么我误解?
- 我该如何解决这个问题?在底部
答
你一个行应该是:
let newHeight = Height(heightInInches: 12)
heightInInches
是要传递给init
方法的参数。
+0
好吧!我输入了它,它似乎工作,但字符串(“转换为...)没有在控制台上打印,我只拿到了20的号码 –
+0
@MichaelFarris你在书中看到了这个注释(重点是我的):*“当一个属性被设置为一个属性时,将调用超类属性的willSet和didSet观察者子类初始化器,在超类初始化器被调用后**在超类初始化器被调用**之前,它们不被调用,而类正在设置它自己的属性。“* – rmaddy
@Shades是正确的。在这种情况下,你可以认为'Height'的行为就像'Class'一样。既然你已经定义了两个入口 - init(heightInIches:)和init(heightInCentimeters:) - ,你不能像这样“实例化”newHeight。 (我还补充说,你可以使用* *,但你的第二行代码表明你想要第一个初始化。 – dfd