Playground 中以下代码的声明给出:
"Return from initializer without initializing all stored properties"
struct Height {
var heightInInches: Double
var heightInCentimeters: Double
init(heightInInches: Double) {
self.heightInInches = heightInInches // here's the compile error
}
init(heightInCentimeters: Double) {
heightInInches = heightInCentimeters * 2.54 // here's the compile error
}
}
请帮我纠正语法。
最佳答案
这就是你想要做的:
struct Height {
var heightInInches: Double
var heightInCentimeters: Double { return heightInInches / 2.54 }
init(heightInInches: Double) {
self.heightInInches = heightInInches
}
init(heightInCentimeters: Double) {
heightInInches = heightInCentimeters * 2.54
}
}
请注意,heightInCentimeters
现在是计算属性而不是存储属性。 (或者,如果不需要的话,您可以删除 heightInCentimeters
。)由于 heightInInches
是一个 var
属性,这可以确保两者始终保持同步。
关于swift - 从初始化器返回而不初始化 Playground 中结构声明的所有存储属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45022129/