Swift - Generic Type Constraint

Introduction

To enforce the types with which your generic function is able to work.

Consider the following example, we added the constraint for the type that your function can accept:

func sortItems< T: Comparable >(inout items:[T]) {
       for var j=0; j<items.count-1; j++ {
           var swapped = false
           for var i=0; i<items.count-1; i++ {
               if items[i]>items[i+1] {
                   swapItems(&items[i], &items[i+1])
                   swapped = true
               }
           }
         if !swapped {
             break
         }
     }
}

The constraint requires that "any type T that conforms to the Comparable protocol."

The function can only accept values of types that implement the Comparable protocol, which allows their values to be compared using the less than operator (>) , greater than operator ( <) , and so on.

Besides the Comparable protocol, you can specify the following protocols:

ProtocolDescription
Equatable determine whether two values are considered to be equal
Printablecustomize the textual representation of any type ready for printing

Besides specifying the protocol that a type needs to implement, you can specify a class type.

For example, the following myFunction() function specifies that T must be an instance of the MyCustomClass class:

func myFunction<T:MyCustomClass >(obj:T) {
...
}

Generic Types

Generics are not limited to functions; you can have generic types.

Generic types can be any of the following:

  • Classes
  • Structures
  • Protocols

Related Topic