Generic functions & types
Write generic functions and types with type parameters (e.g., ). See how the compiler infers types and keeps code safe and reusable.
Why generics?
Generics let you write one function or type that works for many types while staying type-safe. You'll see <T> for type parameters and how inference makes calls simple.
Generic function
A generic function uses a type parameter (<T>). The compiler checks types for each call.
// Generic swap for any type T
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 1, y = 2
swapValues(&x, &y)
print(x, y) // 2 1
var s1 = "A", s2 = "B"
swapValues(&s1, &s2)
print(s1, s2) // B AAll lessons in this course
- Generic functions & types
- Constraints (where), type inference
- Generic algorithms on collections