Swift Function – Find Sum of One or More Ints

To write a function that finds the sum of one or more integer values, we can declare a variadic parameter as shown below.

func sum(_ numbers: Int...) {

Please observe the underscore _ followed by a space before parameter declaration, and the three dots ... after the type in parameter declaration.


In the following example, we will define a function that can accept one or more int values via numbers parameter and find the sum of these values.


func sum(_ numbers: Int...) {
    var result = 0
    for n in numbers {
        result += n
    print("The sum of numbers is \(result)")

sum(2, 3)
sum(1, 2, 8, 4, 6)


Swift Function - Function Sum of One or More Integer Values


In this Swift Tutorial, we learned how to define a function in Swift to accept one or more int values and find their sum.