How to write a generic function for floating point values ​​in swift

I want to call floating point methods on floating point types in swift.

func example<T : FloatingPoint>(_ x:T) -> T {
    return cos(cbrt(x + 1))
}

      

Is there a better way to do this than this?

protocol SupportsFloatingPoint : FloatingPoint {
    var cubeRoot:Self { get }
    var cosine:Self { get }
}

extension Double : SupportsFloatingPoint {
    var cubeRoot:Double { return Darwin.cbrt(self) }
    var cosine:Double { return Darwin.cos(self) }
}

extension Float : SupportsFloatingPoint {
    var cubeRoot:Float { return Darwin.cbrt(self) }
    var cosine:Float { return Darwin.cos(self) }
}

func cbrt<T : SupportsFloatingPoint>(_ x:T) -> T {
    return x.cubeRoot
}

func cos<T : SupportsFloatingPoint>(_ x:T) -> T {
    return x.cosine
}

func example<T : SupportsFloatingPoint>(_ x:T) -> T {
    return cos(cbrt(x - 1))
}

      

Note that the addition operator is lost here. You can use -

, *

and /

, but not +

for SupportsFloatingPoint types.

+3


source to share


1 answer


You don't need a new protocol. You can extend the existing protocol FloatingPoint

for supported types:

// Just for fun :)
prefix operator √
prefix operator βˆ›

extension FloatingPoint where Self == Double {
    var squareRoot: Self { return sqrt(self) }
    var cubeRoot: Self { return cbrt(self) }
    var sine: Self { return sin(self) }
    var cosine: Self { return cos(self) }

    static prefix func √(_ x: Self) -> Self { return x.squareRoot }
    static prefix func βˆ›(_ x: Self) -> Self { return x.cubeRoot }
}

extension FloatingPoint where Self == Float {
    var squareRoot: Self { return sqrt(self) }
    var cubeRoot: Self { return cbrt(self) }
    var sine: Self { return sin(self) }
    var cosine: Self { return cos(self) }

    static prefix func √(_ x: Self) -> Self { return x.squareRoot }
    static prefix func βˆ›(_ x: Self) -> Self { return x.cubeRoot }
}

print(Double.pi.cosine)
print(√25.0)
print(βˆ›8.0)

      



Admittedly, there are a lot of code duplicates that I am currently looking into how to minimize. On the bright side, at least this is all static, inline code that will produce very fast machine code.

+1


source







All Articles