Lesson 37Functions

In-Out Parameters

Modify Original Values

In-out parameters let functions change the original variable you pass in, not just a copy. Use inout and &!

Syntax

func double(_ number: inout Int)

double(&myVariable)

How It Works

1. Copy In

Value copied to function

2. Modify

Function changes value

3. Copy Out

Changed value returns

Rules

  • Must pass a variable (not constant/literal)
  • Must use & when calling
  • Cannot have default values
  • Cannot be variadic parameters

Common Uses

swap()increment()toggle()normalize()
main.swift
// IN-OUT PARAMETERS
// Modify the original variable passed to the function

// PROBLEM: Parameters are constants by default
func tryToDouble(_ number: Int) {
    // number *= 2  // ERROR! Can't modify
}

// SOLUTION: Use inout keyword
func double(_ number: inout Int) {
    number *= 2  // Now we can modify it!
}

var myNumber = 5
double(&myNumber)  // Use & when calling
print(myNumber)    // 10 (original changed!)

// HOW IT WORKS
// 1. Value is copied INTO the function
// 2. Function modifies the copy
// 3. Modified value is copied OUT to original

// PRACTICAL EXAMPLES

// 1. Swap two values
func swap(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var x = 10, y = 20
swap(&x, &y)
print("x: \(x), y: \(y)")  // x: 20, y: 10

// 2. Increment counter
func increment(_ counter: inout Int, by amount: Int = 1) {
    counter += amount
}

var score = 0
increment(&score)       // score is now 1
increment(&score, by: 5)  // score is now 6
print(score)

// 3. Normalize a string
func normalize(_ text: inout String) {
    text = text.lowercased().trimmingCharacters(in: .whitespaces)
}

var input = "  HELLO World  "
normalize(&input)
print(input)  // "hello world"

// 4. Toggle boolean
func toggle(_ value: inout Bool) {
    value = !value
}

var isOn = true
toggle(&isOn)
print(isOn)  // false

// MULTIPLE INOUT PARAMETERS
func rotateLeft(_ a: inout Int, _ b: inout Int, _ c: inout Int) {
    let temp = a
    a = b
    b = c
    c = temp
}

// RULES FOR INOUT
// 1. Must be variables (not constants or literals)
// 2. Must use & when passing
// 3. Cannot have default values
// 4. Cannot be variadic

// WHEN TO USE
// - Modifying multiple values without returning
// - Performance: avoiding copies of large data
// - Matching common patterns like swap

Try It Yourself!

Create a function `clamp(_ value: inout Int, min: Int, max: Int)` that keeps the value within a range!