gpt4 book ai didi

swift - 如何在使用 Swift 3 中的 Measurements 的函数调用中使用泛型

转载 作者:行者123 更新时间:2023-11-28 16:02:17 25 4
gpt4 key购买 nike

我需要一个函数来处理 Swift 3 中任何 Measurement 中的值。下面是一个示例:

var test2 = Measurement<UnitEnergy>( value: 10.1234, unit: .calories)

func printMeasurementGeneric( measurement: Measurement<Unit>) {
print( measurement.value)
}

func printMeasurementEnergy( measurement: Measurement<UnitEnergy>) {
print( measurement.value)
}

printMeasurementEnergy(measurement: test2) // This works
printMeasurementGeneric(measurement: test2) // This doesn't work and give the following error

Playground execution failed: error: Measurement Playground.playground:136:38: error: cannot convert value of type 'Measurement<UnitEnergy>' to expected argument type 'Measurement<Unit>'
printMeasurementGeneric(measurement: test2)

要使 PrintMeasurementGeneric 正常工作,该函数需要看起来像什么?

我取得了一些进展,现在 Swift playground 中有以下代码

var test = Measurement<UnitEnergy>( value: 10.1234, unit: .calories)

func printMeasurementGeneric<A:Dimension>( measurement: Measurement<A>) {
print( measurement.value)
}

// This works
printMeasurementGeneric(measurement: test) // This works

// The following doesn't work
var objectValue: Any?
objectValue = test

var meas = objectValue as! Measurement<Dimension> // Could not cast value of type 'Foundation.Measurement<NSUnitEnergy>' (0x11d324028) to 'Foundation.Measurement<NSDimension>' (0x11d324088).
printMeasurementGeneric(measurement: meas)

我正在尝试使用 NSControl 中的 objectValue 来保存测量值。我如何在检查是否可以将其转换为每种测量类型时执行此操作?

一些更多的工作,包括来自下面的编辑。不是一个漂亮或稳健的解决方案。

var test = Measurement<UnitEnergy>( value: 10.1234, unit: .calories)

func printMeasurementGeneric<A>( measurement: Measurement<A>) {
print( measurement.value)
}

// This works
printMeasurementGeneric(measurement: test) // This works

// The following works but isn't pretty. Is there a better way
var objectValue: Any?
objectValue = test

if objectValue is Measurement<UnitFrequency> {
let meas = objectValue as! Measurement<UnitFrequency>
printMeasurementGeneric(measurement: meas)
} else if objectValue is Measurement<UnitLength> {
let meas = objectValue as! Measurement<UnitLength>
printMeasurementGeneric(measurement: meas)
} else if objectValue is Measurement<UnitSpeed> {
let meas = objectValue as! Measurement<UnitSpeed>
printMeasurementGeneric(measurement: meas)
} else if objectValue is Measurement<UnitEnergy> {
let meas = objectValue as! Measurement<UnitEnergy>
printMeasurementGeneric(measurement: meas)
} else {
print("Didn't find cast!")
}

最佳答案

将您的 PrintMeasurementGeneric 函数更改为此。

func PrintMeasurementGeneric<Dimension>( measurement: Measurement<Dimension>) {
print( measurement.value)
}

我使用了 Dimension 类型而不是 Unit。两者都应该有效,但所有测量类型都符合 Dimension(Unit 的抽象子类)。

Hamish(下)是对的。

关于swift - 如何在使用 Swift 3 中的 Measurements 的函数调用中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40833364/

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