7.2. Closures that return a value

To return a value, we would use -> followed by the return data type followed by in keyword. For example, let's convert the sumOf function into a closure to return the sum of integers in an array.

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

//calling the closure with an integer array
let sum = sumOfArray([1,2,3,4,5])
print(sum)

It prints:

15

Last updated

Was this helpful?