find sum of multiple array elements in swift

To find the sum of multiple array elements in Swift, you can use a loop to iterate through the array and add up the values. Here's an example function that takes an array of integers and returns their sum:

main.swift
func sumOfArrayElements(_ arr: [Int]) -> Int {
    var sum = 0
    for num in arr {
        sum += num
    }
    return sum
}
126 chars
8 lines

You can then call this function with an array of your choice:

main.swift
let numbers = [1, 2, 3, 4, 5]
let sum = sumOfArrayElements(numbers)
print(sum) // Output: 15
93 chars
4 lines

This will output the sum of the numbers in the numbers array, which is 15.

gistlibby LogSnag