Cast CGFloat to Int in extension BinaryFloatingPoint

梦想与她 提交于 2019-12-22 08:11:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!