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:
Syntax
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
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)")
}
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)` 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)
Login to try C/C++/Java/PHP code in the editor
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
- 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: