【发布时间】:2017-09-28 14:15:18
【问题描述】:
我有以下代码:
func roughlyEq<T: FloatingPoint>(_ a: T, _ b: T) -> Bool {
return abs(a - b) < (0.01 as! T)
}
当我使用 Float 类型的参数调用它时,我会在运行时崩溃:
Could not cast value of type 'Swift.Double' (0x10043e6a8) to 'Swift.Float' (0x10043e5e0)
这毫无意义——0.01 确实可以转换为浮点数,比如当我写Float(0.01) 时。为什么会出现这个错误?
相反的方向也失败了:
Could not cast value of type 'Swift.Float' (0x1004ea5e0) to 'Swift.Double' (0x1004ea6a8).
如何让这个方法起作用?
【问题讨论】:
标签: swift casting floating-point type-conversion