swift - 无法在没有参数的情况下为类型 Height 调用初始值设定项

标签 swift properties structure observers

我正在学习 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."

  1. 这是什么意思,我误解了什么?
  2. 我该如何解决这个问题?

最佳答案

你在底部的一行应该是:

 let newHeight = Height(heightInInches: 12)

heightInInches 是您传递给 init 方法的参数。

关于swift - 无法在没有参数的情况下为类型 Height 调用初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018690/

相关文章:

ios - 如果我的应用程序中的方向受限,如何手动确定设备方向?

javascript - 如何枚举 JavaScript 对象的属性?

ios - 在Objective-C中,非原子/赋值顺序在属性声明中是否重要?

javascript - href 属性拒绝在页面加载后重新设置

c - 如何使用 {} 声明指针结构?

ios - ApplicationShortcuts,有什么办法可以不打开应用程序,只执行一些操作,比如播放/暂停?

ios - 导航到同一屏幕,但来自两个不同的 View Controller

swift - 为什么下面的代码会导致无限递归?

c - 在 C 中传递结构

javascript - 悬停选项,或 JavaScript