You can create a type constraint (MyFloats
below) to which your floating point types conform. You let this type constraint itself conform to Comparable
, so that you may make use of the less than binary infix operator <
when comparing the values of your generics. Also, for your example given above, the MyFloats
type constraint need contain only a single blueprint; an initializer for a Double
argument. This initalizer already exists for Double
, Float
and CGFloat
types, but since a protocol cannot know which types that conforms to it, you need to include this blueprint.
protocol MyFloats : Comparable {
init(_ value: Double)
}
extension Double : MyFloats { }
extension Float : MyFloats { }
extension CGFloat : MyFloats { }
func sign<T: MyFloats> (value:T) -> T {
if value < T(0.0) {
return T(-1.0)
}
if value > T(0.0) {
return T(1.0)
}
return T(0.0)
}