swift - 从初始化器返回而不初始化 Playground 中结构声明的所有存储属性错误

标签 swift

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/

相关文章:

ios - 如何在 Swift 中更改 UISearchBar 上 'Cancel' 按钮的颜色

swift - 重启 AVAssetWriter

swift - Metal 中的 ASTC 纹理压缩——我应该使用什么作为每行的字节数?

ios - Swift:在没有 Collection View Controller 的情况下实现 Collection View

xcode - 如果 UITextField 想要第三方键盘中的数字/小数/默认键盘,请捕获?

ios - 在主要目标中包含 pod,而不是在 WatchKit 扩展中

ios - ViewController - 全屏

ios - Swift - 在 UIView 的两个子类中重写一个方法

Swift 3 在索引路径处打破行的单元格

ios - 如何处理 UITableViewController 中的点击单元格