我正在尝试编写通用函数来将计算值与字典中的某些值进行比较 [字符串: (双精度, 双精度)]。
计算值的类型为 Double,但如果应用程序将被扩展并出现一些具有另一种类型的新计算值,则可以重用此函数。但是我无法将双类型与泛型进行比较,我应该更改什么来解决这个问题?
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"
}
您需要使用BinaryFloatingPoint
协议而不是 Numeric 才能强制其值为 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"
你试过吗?
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"
}