๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Variadic and Inout Parameters

A variadic parameter accepts any number of arguments of one type. An inout parameter lets a function change a variable held by its caller.

Summing any count of numbers

The numbers parameter accepts a whole list of Int arguments in one call. The body adds each number in the array it receives.

func total(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
print(total(numbers: 1, 2, 3))
print(total(numbers: 10, 20))

Zero arguments and one argument

The first call passes nothing, so the sum stays at zero. The second call passes a single number.

func total(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
print(total())
print(total(numbers: 7))

Swapping two variables

Both parameters are inout, so the swap writes back into first and second. Each call argument carries an ampersand before the variable name.

func swapValues(a: inout Int, b: inout Int) {
    let temp = a
    a = b
    b = temp
}
var first = 3
var second = 8
swapValues(a: &first, b: &second)
print(first)
print(second)

Example

func addBonus(score: inout Int, bonus: Int) {
    score += bonus
}
var points = 40
addBonus(score: &points, bonus: 15)
print(points)
addBonus(score: &points, bonus: 5)
print(points)

Key points

  • A variadic parameter writes its type followed by three dots.
  • Inside the function, a variadic parameter behaves as an array of its type.
  • A call can pass no argument for a variadic parameter, and the array is then empty.
  • An inout parameter carries the inout mark before its type in the definition.
  • A call writes an ampersand before a variable passed to an inout parameter.
  • A change made to an inout parameter shows in the caller variable after the call.

In this example, the addBonus function adds its bonus argument to the score parameter. The first call passes points with an ampersand and raises it from 40 to 55. The second call raises the same variable to 60.

Note

An inout argument must be a variable, not a constant or a plain value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What mark goes before a variable passed to an inout parameter?