我有一个函数接受符合以下条件的值Numeric协议,在某些时候我想将其转换为Int, Double or CGFloat.
来自 xCode 的错误:
Initializer 'init(_:)' requires that 'T' conform to 'BinaryInteger'
我的功能:
func test<T: Numeric>(value1: T, value2: T) {
let someWork = value1 + value2
let intValue: Int = Int(someWork) // <<: Here!
let doubleValue: Double = Double(someWork) // <<: Here!
let cgflotValue: CGFloat = CGFloat(someWork) // <<: Here!
print(intValue, doubleValue, cgflotValue)
}
然后我看到 xCode 错误并将我的函数更新为这个向下版本,我推出Numeric因为二进制整数 and 二进制浮点符合Numeric
func test<T: BinaryInteger & BinaryFloatingPoint>(value1: T, value2: T) {
let someWork = value1 + value2
let intValue: Int = Int(someWork) // <<: Here: I add BinaryInteger because of Int
let doubleValue: Double = Double(someWork) // <<: Here: I add BinaryFloatingPoint because of Double
let cgflotValue: CGFloat = CGFloat(someWork) // <<: Here: I add BinaryFloatingPoint because of CGFloat
print(intValue, doubleValue, cgflotValue)
}
用例:
let testValue1: Int = 2
test(value1: testValue1, value2: testValue1)
用例的 xCode 错误:
Global function 'test(value1:value2:)' requires that 'Int' conform to 'BinaryFloatingPoint'
用例:
let testValue2: Double = 2.0
test(value1: testValue2, value2: testValue2)
用例的 xCode 错误:
Global function 'test(value1:value2:)' requires that 'Double' conform to 'BinaryInteger'
我怎样才能使Int符合二进制浮点?
Or:
我怎样才能使双精度/CG浮点符合二进制整数?
正如您在 xCode 错误中看到的那样。