6.3. Functions that return a value

Now, let's think about a function that accepts an array of integers as a parameter and returns the sum of the integers.

func sumOf(array:[Int]) -> Int{
    var sum = 0
    for item in array{
        sum += item
    }
    
    //returns the value...
    return sum
}

//calling the function with an integer array
print(sumOf(array: [1,2,3,4,5]))

It prints:

15

You can get the returned value and store it to a constant or variable:

let sum = sumOf(array: [1,2,3,4,5])

Last updated

Was this helpful?