考虑以下内容(从实际代码中简化而来):
func roundedInt<T: FloatingPoint>(_ f: T) -> Int {
return Int(f.rounded())
}
编译失败,出现以下错误:
Cannot invoke initializer for type 'Int' with an argument list of type '(T)' Overloads for 'Int' exist with these partially matching parameter lists: (Int64), (Word), (UInt8), (Int8), (UInt16), (Int16), (UInt32), (Int32), (UInt64), (UInt), (Int), (Float), (Double), (Float80), (String, radix: Int), (CGFloat), (NSNumber)
我认为这意味着 FloatingPoint 无法与任何 Int 重载相匹配。
有没有一种简单的方法来完成这项工作?或者 Swift 泛型是否有限制(例如,与 C++ 模板相比)排除了这一点?
最佳答案
使用 BinaryFloatingPoint
这会如您所愿,在 Int 可以表示的范围内。
func roundedInt<T: BinaryFloatingPoint>(_ f: T) -> Int {
return Int(f.rounded())
}
let x = roundedInt(Float(42.1)) // 42
关于Swift:将通用的 FloatingPoint 值转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706023/