我正在尝试编写通用函数来比较计算值与 [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"
}
最佳答案
您需要使用 BinaryFloatingPoint
协议(protocol)而不是 Numeric 才能将其值强制为 Double,创建一个范围并检查它是否包含您的 cosAngle(注意:可以删除 Comparable 约束,因为它包含不要求元素是可比较的,只要求是可等同的):
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"
关于swift - 我如何比较通用类型和 double 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53932076/