Constraints

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Constraints

When you define a generic function or type, you can set constraints on the types that may be used. Constraints can be protocols or classes, and the syntax is <T: Protocol> or <T: Class>.

<T: Protocol>

The generic function swapValues<T> works with all types, but consider this generic function:

<T: Class>

Another class in the same module is VehicleType, which has a move method:

Where Clause

Use where when you need to set more than one constraint, for example, if T must inherit from the VehicleType class and also conform to the Comparable protocol:

See forum comments
Download course materials from Github
Previous: Generics Next: Generics - Conclusion