0Pricing
Swift Academy · Lesson

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 A

All lessons in this course

  1. Generic functions & types
  2. Constraints (where), type inference
  3. Generic algorithms on collections
← Back to Swift Academy