我正在学习 Apple 的 App Development With Swift iBook,在结构章节之前一直很顺利,特别是在属性观察器部分。我的任务是检查单位换算。
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 文档,我认为这应该可行。但是我收到一条错误消息,指出:
"Cannot invoke initializer for type 'Height' with no arguments."
- 这是什么意思,我误解了什么?
- 我该如何解决这个问题?
最佳答案
你在底部的一行应该是:
let newHeight = Height(heightInInches: 12)
heightInInches
是您传递给 init
方法的参数。
关于swift - 无法在没有参数的情况下为类型 Height 调用初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018690/