Variadic functions in swift

Variadic Functions in Swift

(Last Updated On: September 25, 2021)

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

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

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

Let’s see how you can create your own variadic function.

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 functions 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 the 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

That’s It. You now know how to create Variadic Functions in Swift. Cheers.

1 Comment

Leave a Comment