gpt4 book ai didi

swift - 快速接受任何类型测量的功能

转载 作者:行者123 更新时间:2023-12-04 00:53:25 25 4
gpt4 key购买 nike

Swift 实现了 Measurement类型,可用于将速度、高度等值保存在所需的度量中。

例如:

// Going to explicitly type here so the question is clear

var speed: Measurement<UnitSpeed> = Measurement(value: 10, unit: UnitSpeed.metersPerSecond)
var altitude: Measurement<UnitLength> = Measurement(value: 500, unit: UnitLength.meters)

altitude.convert(to: UnitLength.feet)

print("500 meters is roughly \(Int(altitude.value)) feet")
// Prints: 500 meters is roughly 1640 feet

然而,即使UnitLengthUnitSpeed都是 Unit 的子类,使用这些类型的测量不能以多态方式传递到 swift 中的函数中。

例如,如果你传入一个类型为Measurement<UnitLength>的对象,下面的函数就不起作用了或 Measurement<UnitSpeed> .

func formatMeasurementAsString(measurement: Measurement<Unit>) -> String {
return "\(Int(measurement.value)) \(measurement.unit.symbol)"
}

传入 speedaltitude上面定义到此函数中会产生以下错误:Cannot convert value of type 'Measurement<UnitSpeed>' to expected argument type 'Measurement<Unit>'

编辑:

所以你可以显式地输入 speedaltitude在本例中为类型 Measurement<Unit> .但是,如果您这样做,他们将失去非常有用的 .convert(to:)。函数,除非你将它们类型转换回 Measurement<UnitLength>在转换之前,这不是很有帮助。

最佳答案

你可以使函数通用

func formatMeasurementAsString<T: Unit>(measurement: Measurement<T>) -> String {
return "\(Int(measurement.value)) \(measurement.unit.symbol)"
}

例子

let length = Measurement(value: 180.0, unit: UnitLength.meters)
let speed = Measurement(value: 60, unit: UnitSpeed.kilometersPerHour)

print(formatMeasurementAsString(measurement: length))
print(formatMeasurementAsString(measurement: speed))

180 m
60 km/h

关于swift - 快速接受任何类型测量的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64613792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com