gpt4 book ai didi

swift - 如何在 Swift 中使用 Double 进行乘法、加法等... SignedNumber?

转载 作者:可可西里 更新时间:2023-11-01 01:57:34 26 4
gpt4 key购买 nike

我尝试构建一个有点通用的插值函数:

func interpolateNumber<T:SignedNumeric> (_ x0:T, with x1:T, bounds:ClosedRange<Double>, at:Double) -> Double{
return x0 + (x1-x0) * (at-bounds.lowerBound)/(bounds.upperBound-bounds.lowerBound)
}

但是编译器提示:

Binary operator '*' cannot be applied to operands of type 'T' and 'Double'

Bounds.lowerBound 和 .upperBound 是 Double,它们应该是。如何将“*”运算符应用于 SignedNumeric 和 Double?

最佳答案

不幸的是,SignedNumeric 协议(protocol)没有使用 /* 运算符。因此,您必须将 T 类型转换为更具体的类型。这是一种不太漂亮的方法:

func interpolateNumber<T: SignedNumeric>(_ x0: T, with x1: T, bounds: ClosedRange<Double>, at: Double) -> Double {
var x0Final: Double!
var x1Final: Double!

switch T.self {
case is Double.Type:
x0Final = x0 as! Double
x1Final = x1 as! Double
case is Float.Type:
x0Final = Double(x0 as! Float)
x1Final = Double(x1 as! Float)
case is Float32.Type:
x0Final = Double(x0 as! Float32)
x1Final = Double(x1 as! Float32)
case is Float64.Type:
x0Final = Double(x0 as! Float64)
x1Final = Double(x1 as! Float64)
case is Float80.Type:
x0Final = Double(x0 as! Float80)
x1Final = Double(x1 as! Float80)
case is Int.Type:
x0Final = Double(x0 as! Int)
x1Final = Double(x1 as! Int)
case is Int8.Type:
x0Final = Double(x0 as! Int8)
x1Final = Double(x1 as! Int8)
case is Int16.Type:
x0Final = Double(x0 as! Int16)
x1Final = Double(x1 as! Int16)
case is Int64.Type:
x0Final = Double(x0 as! Int64)
x1Final = Double(x1 as! Int64)
default:
fatalError("Binary operator '*' cannot be applied to operands of type '\(T.self)' and 'Double'")
}

return x0Final + (x1Final - x0Final) * (at - bounds.lowerBound) / (bounds.upperBound - bounds.lowerBound)
}

print(interpolateNumber(3.0, with: 4, bounds: 0...10, at: 0.7)) // Prints 3.07
print(interpolateNumber(3, with: 4, bounds: 0...10, at: 0.7)) // Prints 3.07

关于swift - 如何在 Swift 中使用 Double 进行乘法、加法等... SignedNumber?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50584029/

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