Variadic Parameters in Swift

Variadic paramaters are those which accept from zero to N number of parameters.

The most common method which you use almost daily is print() method

You can do print(“abc”) or you can also do print(“a”,”b”,”c”,”d”) or any number of paramters and it will print it all.

Lets see how you can create your own function using variadic parameters.

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


let sum = addition(0,1,2,3,4,5,6,7,8,9)
print(sum) // 45

You can see in the above code instead of just saying Int, I have entered Int… i.e. Int with three dots. This is how variadic parameters are declared. Now, numbers will be an array of Int type and you may use for loop to sum the numbers. Or you can also reduce it to below code:

func addition(_ numbers : Int...) -> Int {
    return numbers.reduce(0, +)
}

let sum = addition(0,1,2,3,4,5,6,7,8,9)
print(sum) // 45

Thats It. You now know how to create Variadic Parameters in Swift. Cheers.

1 Comment

Leave a Comment