Search code examples
swiftgeneric-programming

Swift - How to write generic max function


I'm new to Swift and I want to write a generic max function which compares the two parameter and returns the larger one, for basic types like Int, Double, etc.

func max<T>(_ num1:T, _ num2:T) -> T {
    return (num1 > num2) ? num1 : num2;
}

But I found this does't work, reported that Binary operation '>' cannot be applied to two 'T' operand.

I saw an example about generic add function Here

protocol Summable { static func +(lhs: Self, rhs: Self) -> Self }
extension Int: Summable {}
extension Double: Summable {}

func add<T: Summable>(x: T, y: T) -> T {
  return x + y
}

So I think I should have a protocol for my max function, too. So this is my attempt:

protocol Comparable {
    static func >(lhs: Self, rhs: Self) -> Self
}
extension Int:Comparable {}
extension Double:Comparable {}

But this doesn't work. I know there is a provided Comparable protocol from Swift, but I want to try it myself. Could you please help?


Solution

  • protocol TempComparable {
        static func >(lhs:Self, rhs:Self) -> Bool;
    }
    
    func max<T:TempComparable>(_ num1:T, _ num2:T) -> T {
        return (num1 > num2) ? num1 : num2;
    }