Generic Functions / Type Parameters
Swift generic functions let you write reusable logic that is not tied to a specific type. By using a type parameter (e.g., T), you can define a single function that works with multiple types.
Syntax
// Defining a generic function
func functionName<T>(argument: T) -> T {
// Work with T
}
// With a type constraint (T must conform to Comparable)
func functionName<T: Comparable>(a: T, b: T) -> T {
return a < b ? a : b
}
// Multiple type parameters
func functionName<T, U>(t: T, u: U) {
// Work with T and U
}
Syntax Overview
| Syntax | Description |
|---|---|
| func name<T>(...) | Defines a generic function with type parameter T. |
| <T: Protocol> | Adds a type constraint. T must conform to the specified protocol. |
| <T, U> | Defines multiple type parameters. |
| Type inference | The compiler infers the type parameter from the argument at the call site, so you do not need to specify it explicitly. |
Sample Code
// A type-independent swap function
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 10, y = 20
swapValues(&x, &y)
print("x: \(x), y: \(y)") // x: 20, y: 10
var s1 = "hello", s2 = "world"
swapValues(&s1, &s2)
print("\(s1) \(s2)") // world hello
// Type constraint: restricted to types that conform to Comparable
func minimum<T: Comparable>(_ a: T, _ b: T) -> T {
return a < b ? a : b
}
print(minimum(3, 7)) // 3
print(minimum("apple", "banana")) // apple
// Generic function to search for an element in an array (Equatable constraint)
func findIndex<T: Equatable>(_ array: [T], _ target: T) -> Int? {
for (i, item) in array.enumerated() {
if item == target { return i }
}
return nil
}
let numbers = [10, 20, 30, 40, 50]
if let idx = findIndex(numbers, 30) {
print("30 is at index \(idx)")
}
let words = ["swift", "kotlin", "rust"]
if let idx = findIndex(words, "kotlin") {
print("kotlin is at index \(idx)")
}
Notes
A generic function uses a type placeholder in place of a concrete type. The compiler infers the type parameter from the arguments passed at the call site, so you do not need to specify the type explicitly.
Adding a type constraint (T: Protocol) allows you to use the methods and properties provided by that protocol inside the function. Without a type constraint, you can only use operations that are available on all types.
For generic types, see Generic Types / where Clause.
If you find any errors or copyright issues, please contact us.