无法在没有参数的情况下为类型 Height 调用初始值设定项
Cannot invoke initializer for type Height with no arguments
我正在使用 Swift iBook 学习 Apple 的 App Development,在结构章节之前一直很顺利,特别是在 属性 观察者部分。我的任务是检查单位换算。
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 iBook 学习 Apple 的 App Development,在结构章节之前一直很顺利,特别是在 属性 观察者部分。我的任务是检查单位换算。
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
方法的参数。