I have a function which accept values which conform to Numeric protocol, in some point I want convert it to Int, Double or CGFloat.
the error from xCode:
Initializer 'init(_:)' requires that 'T' conform to 'BinaryInteger'
my function:
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)
}
then I saw the xCode error and updated my function to this down version, I put out Numeric because BinaryInteger and BinaryFloatingPoint conform to 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)
}
use case:
let testValue1: Int = 2
test(value1: testValue1, value2: testValue1)
xCode error for use case:
Global function 'test(value1:value2:)' requires that 'Int' conform to 'BinaryFloatingPoint'
use case:
let testValue2: Double = 2.0
test(value1: testValue2, value2: testValue2)
xCode error for use case:
Global function 'test(value1:value2:)' requires that 'Double' conform to 'BinaryInteger'
How can I make Int conform to BinaryFloatingPoint?
Or:
How can I make Double/CGFloat conform to BinaryInteger?
as you see in xCode errors.