SyntaxStudy
Sign Up
Swift inout Parameters and Generic Functions
Swift Beginner 1 min read

inout Parameters and Generic Functions

Swift passes function arguments by value by default. The inout keyword allows a function to modify a variable in the caller's scope — pass the argument with & prefix. Generic functions work with any type satisfying given constraints. Type parameters are declared in angle brackets and can be constrained with where clauses or protocol conformances. Generic functions combined with protocol constraints enable reusable algorithms that work across many types.
Example
// inout parameters
func swap<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}
var x = 10, y = 20
swap(&x, &y)
print(x, y)  // 20 10

// Generic function with constraint
func findFirst<T: Equatable>(_ item: T, in array: [T]) -> Int? {
    for (index, element) in array.enumerated() {
        if element == item { return index }
    }
    return nil
}
findFirst("banana", in: ["apple", "banana", "cherry"])  // Optional(1)

// Multiple constraints
func showMax<T: Comparable & CustomStringConvertible>(_ a: T, _ b: T) -> String {
    let max = a > b ? a : b
    return "Max: \(max.description)"
}

// Where clause on generic
func allUnique<T: Hashable>(_ array: [T]) -> Bool {
    Set(array).count == array.count
}
allUnique([1, 2, 3, 4])   // true
allUnique([1, 2, 2, 4])   // false

// Generic type with associated type protocol
protocol Stack {
    associatedtype Element
    mutating func push(_ item: Element)
    mutating func pop() -> Element?
    var top: Element? { get }
}