Generic functions

Let's consider the following code, which isn't implemented with generics:

func compareInts(_ a: Int, _ b: Int) -> Int {
if a > b { return 1 }
if a < b { return -1 }
return 0
}

This works with integers, but how would it work with Double? We'd need to implement another method:

func compareDoubles(_ a: Double, _ b: Double) -> Int {
if a > b { return 1 }
if a < b { return -1 }
return 0
}

Generics-based programming aims to resolve this issue. In Swift, we have the Comparable protocol, which we can use in order to implement a generic compare function:

func compare<T>(_ a: T, _ b: T) -> Int where T: Comparable {
if a > b { return 1 }
if a < b { return -1 }
return 0
}

Let's break it down:

With this method, we can use it with any type that is Comparable.