Variadic Parameters

Variadic parameters allow you to pass as many parameters into a function as your heart desires. If you have worked in Objective-C then you know that doing this in Objective-C requires a nil terminator so that things don’t break. Swift does not require such strict rules. Swift makes it easy to implement unlimited parameters by using an ellipsis, which is three individual periods (...). You tell Swift what type you want to use, add an ellipsis, and you’re done.

The following function finds the average of a bunch of ints:

func average(numbers: Int...) -> Int {    var total = 0    for n in numbers {        total += n    }    return total / numbers.count}

It would be nice if you could pass in any number ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.