在扩展BinaryFloatingPoint中将CGFloat转换为Int

时间:2018-03-16 16:55:49

标签: swift casting int cgfloat

  

在SWIFT 4.2中修复

详细

Xcode 9.2,Swift 4

代码

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)
    }
}

错误发生

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

enter image description here

问题

为什么

Int(cgfloat) // No Error

cgfloat.toInt() // Thread 1: Fatal error: Conversion 

???

在这两种情况下,都会发生相同类型的转化Int(value)。我的扩展使用Float和Double类型,但只发生CGFloat错误。 它是一个Swift语言错误吗?

0 个答案:

没有答案