Compute two different FloatingPoint vars

Hi,
i need a function which could deliver me result from two different FloatingPoint numbers:

func div<T1:FloatingPoint, T2:FloatingPoint>(a:T1, b:T2) -> T1 {
   // return a/b // will not work — Cannot convert value of type 'T2' to expected argument type 'T1', understand
   return a/T1(b) //  I don't understand an error — „Initializer 'init(_:)' requires that 'T2' conform to 'BinaryInteger'”
}

I need to compute results from Double and CGFloat, but why not others? Is it somehow possible?

There is no such converting initializer on FloatingPoint (that protocol doesn’t offer enough guarantees to make such a generic conversion implementable); use BinaryFloatingPoint instead as your constraint.

The quality of the diagnostic is poor: it shouldn’t suggest conforming to BinaryInteger.

Note that there is a possible performance penalty to using a generic conversion when you don’t absolutely need it; if you’re always converting from or to the same type, use the concrete type instead :)

1 Like

I have to choose between converting many CGFloats to Doubles, or little less Doubles to Doubles... Hard decision.
So simple! Thank you!

In an upcoming version of Swift, conversions from CGFloat to Double and vice versa will be implicit, so you will be able to use Double throughout your own code and not have to write anything to use APIs that take CGFloat values.

3 Likes
Terms of Service

Privacy Policy

Cookie Policy