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:
- <T> indicates that this function is generic, and one type, T, will be used in it
- a: T, b: T indicates that this method takes two parameters of the T type
- where T: Comparable indicates that T is required to conform to the Comparable protocol
With this method, we can use it with any type that is Comparable.