我尝试构建一个通用插值函数:
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?
答案 0 :(得分:1)
不幸的是SignedNumeric
协议没有/
和*
运算符。因此,您必须将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