What are Generics?
Generics allow you to write flexible, reusable functions and types that can work with any data type, while still maintaining full type safety. You use angle brackets
<T> to define a type parameter.swift
Generic Types
You can make entire classes, structs, and enums generic.
swift
Type Constraints
Wait! Sometimes you need to restrict a generic type to only work with types that have certain capabilities (like being able to be compared).
swift
The where Clause
For more complex constraints, you can use the
where clause.swift
Summary
| Term | Description |
|---|---|
| T | Convention for Type Parameter |
| Element | Convention for collection items |
| Equatable | Protocol for types that can be compared (==) |
| Comparable | Protocol for types that can be ordered (<, >) |
| Constraint | Restricting the types that can be used |
| Best For | Collections (Array, Dictionary) and reusable logic |
| Logic | "Write once, run for any type safely" |
| Safety | Catch type-related bugs at compile-time |
| Modern | Opaque types (some Protocol) are built on generics |
| Standard | The foundation of the Swift Standard Library |
| Identity | Generics are specialized by the compiler for maximum speed |
| Where | Custom logic for complex generic requirements |