Variadic Functions in Swift

Here’s a function that will take an arbitrary number of ints as arguments.

import Foundation

func sum(_ nums: Int...) {
    print(nums, terminator: "")
    var total = 0
    for num in nums {
        total += num
    }
    print(" \(total)")
}

sum(1, 2)
sum(1, 2, 3)

let nums = [1, 2, 3, 4]
sum(nums)

Variadic functions can be called in the usual way with individual arguments.

If you already have multiple args in an array, apply them to a variadic function using the spread operator nums... like this.

let nums = [1, 2, 3, 4]
sum(nums...)

You can run this program by pasting the code into a Swift playground or saving it into a .swift file and running it with the Swift command-line tools.

$ swiftc sum.swift -o sum
$ ./sum
[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10

Another key aspect of functions in Swift is their ability to form closures, which we’ll look at next.

Next example: Closures.