我正在尝试编写泛型函数以将计算值与[String:(Double,Double)]类型的字典中的某些值进行比较。
计算值的类型为Double,但是如果应用程序将被扩展并出现其他类型的新计算值,则可以重用此函数。但是我无法将Double类型与Generic进行比较,该如何解决呢?
let angleDict = ["Snatch": (-1.0, -0.9962),
"Thruster": (-1.0, -0.9962),
"Ringdip": (0.0, 0.9998),
"Burpee": (0.1736, 0.9998),
"Push Up": (0.0, 0.9998),
"Back Squat": (0.0, 0.9998)]
func probeResult<T: Numeric & Comparable>(exerciseName: String, cosAngle: T) -> String{
return cosAngle > angleDict[exerciseName]!.0 && cosAngle < angleDict[exerciseName]!.1 ? "OK" : "WRONG"
}
答案 0 :(得分:3)
您需要使用BinaryFloatingPoint
协议而不是数字协议才能将其值强制为Double,创建一个范围并检查其是否包含cosAngle(注意:考虑到包含不包含可比较约束,可以删除可比较约束要求元素是可比较的,只有相等的):
func probeResult<T: BinaryFloatingPoint>(exerciseName: String, cosAngle: T) -> Bool {
guard
let lower = angleDict[exerciseName]?.0.nextUp,
let upper = angleDict[exerciseName]?.1
else { return false }
return lower..<upper ~= Double(cosAngle)
// or
// return T(lower)..<T(upper) ~= cosAngle
}
let result = probeResult(exerciseName: "Back Squat", cosAngle: CGFloat(0.5)) ? "OK" : "WRONG"
答案 1 :(得分:0)
您是否尝试过如下所示?
func probeResult<T: Numeric & Comparable>(exerciseName: String, cosAngle: T) -> String{
var d = 0.0
switch cosAngle {
case let value as Int:
d = Double(value)
case let value as Int32:
d = Double(value)
case let value as Double:
d = value
default:
break
}
return d > angleDict[exerciseName]!.0 && d < angleDict[exerciseName]!.1 ? "OK" : "WRONG"
}