← Back to Swift Course | Chapter 12: Generics & Advanced Types | Lesson 1 of 7

Generic Functions

A generic function is written once but works with almost any type you throw at it, like a universal adapter.

Writing a Generic Function

A generic function declares a placeholder type in angle brackets after its name, which then stands in for whatever concrete type is used when it's called.

Example: Writing a Generic Function

markup
func firstAndLast<T>(_ items: [T]) -> (T, T)? {
    guard let first = items.first, let last = items.last else { return nil }
    return (first, last)
}
if let result = firstAndLast([1, 2, 3, 4]) {
    print("First: \(result.0), Last: \(result.1)")
}
if let result = firstAndLast(["a", "b", "c"]) {
    print("First: \(result.0), Last: \(result.1)")
}

Multiple Generic Placeholders

A generic function can declare more than one placeholder type, letting it work across combinations of different types at once.

Example: Multiple Generic Placeholders

markup
func makePair<A, B>(_ first: A, _ second: B) -> (A, B) {
    return (first, second)
}
let pair = makePair(1, "one")
print(pair)
Common Mistakes
  1. Writing near-identical functions for Int, String, Double, etc. when a single generic function with a placeholder type would work for all of them.
  2. Forgetting the placeholder type name (like T) must be declared in angle brackets right after the function name.
  3. Assuming a generic placeholder T can do anything; it only supports operations valid for every possible type, unless constrained further.
Chapter Summary
  • A generic function uses a placeholder type, conventionally T, declared in angle brackets.
  • The placeholder stands in for a real type determined at the call site.
  • Generic functions avoid duplicating logic across multiple concrete-typed versions.
  • Without constraints, a generic type only supports operations valid for any type at all.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.