我正在使用Swift iBook进行Apple的应用程序开发,直到结构章节,特别是在属性观察者部分,它一直很顺利。我的任务是检查单位转换。
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'调用初始值设定项。”
答案 0 :(得分:0)
你底部的一行应该是:
let newHeight = Height(heightInInches: 12)
heightInInches
是您传递给init
方法的参数。