Variadic parameter
In Swift, a variadic parameter is denoted by placing three periods (...) after the parameter's type in a function declaration. A variadic parameter allows a function to accept any number of arguments of the specified type.
Here's an example of a function that accepts a variadic parameter:
func sum(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
In this function, numbers are a variadic parameter of type Int. It can accept any number of arguments of type Int. The function then adds up all the numbers and returns the total.
Here's an example of calling the sum function with multiple arguments:
let total = sum(numbers: 1, 2, 3, 4, 5)
print(total) // Output: 15
In this example, the sum function is called with five arguments: 1, 2, 3, 4, and 5. The function adds these numbers up and returns the total, which is then printed to the console.
To keep in mind when using variadic parameters in Swift:
- A function can have only one variadic parameter, and it must be the last parameter in the parameter list.
- You can pass zero or more values when calling a function with a variadic parameter. If you pass zero values, the parameter will be an empty array of the specified type.
- You can use the count property of the variadic parameter to get the number of values passed to the function.
- You can also use the spread operator (...) to pass an array or sequence of values as a variadic parameter.
Comments
Post a Comment