TIL how to extend all floating point types at ones in Swift
About a month ago, on 13 of January, I have written about exnending all float types (Float
, CGFloat
, Double
and Float80
) at once by extending FloatingPoint
. This day come. After writing 100 times function for conversion from degrees to radians and vise versa I decided it’s time to write something generic. It turns out not to be that easy.
Intension is to write following, but generic:
extension Double {
var inRadians: Double {
return self / (180.0 * Double.pi)
}
}
This is working:
extension BinaryFloatingPoint {
func inRadians<T>() -> T where T: BinaryFloatingPoint {
return T(self) / (T(180.0) * T.pi)
}
}
First, failed to make it for FloatingPoint
just because haven’t found way to cast literal 180.0
(which is Double
) to FloatingPoint
. Strange. Second, appearance of T
here is artificial. There’s no way to get rid of T
and use just BinaryFloatingPoint
. Third, I haven’t found a syntax to make it work for property, not for a function. Should be possible something like this, but it isn’t working:
extension BinaryFloatingPoint {
var inRadians: <T> where T: BinaryFloatingPoint { // compiler gets mad here
return T(self) / (T(180.0) * T.pi)
}
}