swift - 我的解决方案对问题是否正确?成员构造器和自定义构造器

标签 swift

创建一个具有两个变量属性 heightInInches 和 heightInCentimeters 的 Height 结构。两者都应该是 Double 类型。

创建两个自定义初始化程序。一个初始化程序将采用一个 Double 参数来表示以英寸为单位的高度。另一个初始化器将采用一个 Double 参数来表示以厘米为单位的高度。每个初始化器都应该获取传入的值并使用它来设置与传入的度量单位相对应的属性。然后它应该通过根据传入的值计算正确的值来设置其他属性。提示:1 英寸 = 2.54 厘米。

struct Height{
    var heightInInches :Double=0.0
    var heightInCentimeters :Double=0.0

    init(inches:Double) {
        heightInInches=inches * 2.54
    }
    init(centimeters:Double) {
        heightInCentimeters=centimeters/2.54

    }


}
let inch = Height(inches:65)
print(inch.heightInInches)

let centi=Height(centimeters:65)
print(centi.heightInCentimeters)

如果您使用英寸的初始化程序来传递 65 的高度,则初始化程序应将 heightInInches 设置为 65 并将 heightInCentimeters 设置为 165.1。

最佳答案

备份一秒钟并隔离每个需求

One initializer will take a Double argument that represents height in inches. The other initializer will take a Double argument that represents height in centimeters.

Each initializer should take the passed in value and use it to set the property that corresponds to the unit of measurement passed in.

这可能看起来像...

init(inches:Double) {
    heightInInches = inches
}

init(centimeters:Double) {
    heightInCentimeters = centimeters
}

It should then set the other property by calculating the right value from the passed in value. Hint: 1 inch = 2.54 centimeters.

这可能看起来更像这样......

init(inches:Double) {
    heightInInches = inches
    heightInCentimeters = inches * 2.54
}
init(centimeters:Double) {
    heightInInches = centimeters / 2.54
    heightInCentimeters = centimeters
}

然后这允许您将属性设置为 let 并避免变异 struct 的所有问题

struct Height{
    let heightInInches: Double
    let heightInCentimeters: Double

    init(inches:Double) {
        heightInInches = inches
        heightInCentimeters = inches * 2.54
    }
    init(centimeters:Double) {
        heightInInches = centimeters / 2.54
        heightInCentimeters = centimeters

    }
}

这是最好留到改天再上的课 ;)

关于swift - 我的解决方案对问题是否正确?成员构造器和自定义构造器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56828741/

相关文章:

ios - 如何在 iOS 应用程序中停止 captureOutput

ios - XCode 6/Swift - 将 google admob 设置指令从 objective-c 转换为 Swift

ios - 尝试理解委托(delegate)

swift - Swift 中从 userInfo 获取键盘大小

swift - 如何在 Swift 中以二进制形式打开文件

arrays - Swift - 在数组中搜索数字模式

swift - 将视频(和属性)上传到 vimeo 的 RESTful 机制

swift - 将 base64 字符串作为 PDF 显示到 Web View 中

ios - 如何去除IOS App swift上top Bar的透明度

swift - 使用防护/if 语句来设置多个 CollectionvViewCell 样式的良好做法?