Type constraints with Generics
A type constraint specifies that a generic type must inherit from a specific class or conform to a particular protocol. This allows us to use the methods or properties defined by the parent class or protocol with the generic types. Let's look at how to use type constraints by rewriting the genericEqual()
function to use the Comparable
protocol:
func testGenericComparable<T: Comparable>(a: T, b: T) -> Bool{ return a == b }
To specify the type constraint, we put the type or protocol constraint after the generic placeholder, where the generic placeholder and the constraint are separated by a colon. This new function works as we might expect, and it will compare the values of the two parameters and return true
if they are equal or false
if they are not.
We can declare multiple constraints just like we declare multiple generic types. The following example shows how to declare two generic types with different constraints:
func testFunction<T: MyClass...