Generic Functions
A generic function is written once but works with almost any type you throw at it, like a universal adapter.
In this page:
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
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)")
}
Login to try C/C++/Java/PHP code in the editor
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
func makePair<A, B>(_ first: A, _ second: B) -> (A, B) {
return (first, second)
}
let pair = makePair(1, "one")
print(pair)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing near-identical functions for
Int,String,Double, etc. when a single generic function with a placeholder type would work for all of them. - Forgetting the placeholder type name (like
T) must be declared in angle brackets right after the function name. - Assuming a generic placeholder
Tcan 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: