FIXED IN SWIFT 4.2
Details
Xcode 9.2, Swift 4
Code
extension BinaryFloatingPoint {
func toInt() -> Int {
// Eror if remove this block (I do not know why)
// if let value = self as? CGFloat {
// return Int(value)
// }
return Int(self)
}
}
Error occurrence
let float: Float = 2.38945
print("Float: \(float.toInt())") // No Error
let double = Double(float)
print("Double: \(double.toInt())") // No Error
let cgfloat = CGFloat(float)
print("CGFloat(): \(Int(cgfloat))") // No Error
print(".toInt(): \(cgfloat.toInt())") // Thread 1: Fatal error: Conversion is not supported
Question
Why
Int(cgfloat) // No Error
but
cgfloat.toInt() // Thread 1: Fatal error: Conversion
???
In both cases, the same type conversions Int(value)
occur. My extension works with Float and Double types, but only with CGFloat error occurs.
Does it a Swift language bug?
来源:https://stackoverflow.com/questions/49325962/cast-cgfloat-to-int-in-extension-binaryfloatingpoint