← 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.
Syntax
swift
func functionName<T>(_ param: T) -> T {
    return param
}

func functionName<A, B>(_ a: A, _ b: B) -> (A, B) {
    return (a, b)
}

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)` from this function
    return (first, last)
}
// If `firstAndLast([1, 2, 3, 4])` has a value, bind it to `result`
if let result = firstAndLast([1, 2, 3, 4]) {
    // Print "First: \(result.0), Last: \(result.1)" to the console
    print("First: \(result.0), Last: \(result.1)")
}
// If `firstAndLast(["a", "b", "c"])` has a value, bind it to `result`
if let result = firstAndLast(["a", "b", "c"]) {
    // Print "First: \(result.0), Last: \(result.1)" to the console
    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)` from this function
    return (first, second)
}
// Declare a constant `pair`, set to `makePair(1, "one")`
let pair = makePair(1, "one")
// Print `pair` to the console
print(pair)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.