find the sum of a list of numbers in swift

To find the sum of a list of numbers in Swift, you can use a loop to iterate through the array and add each number to a running total variable. Here's an example code block:

main.swift
let numbers = [1, 2, 3, 4, 5]
var sum = 0

for number in numbers {
    sum += number
}

print("The sum is: \(sum)") // Output: The sum is: 15
142 chars
9 lines

In this example, we create an array of numbers, initialize a variable sum to 0, and then iterate through each number in the array using a for loop. In each iteration of the loop, we add the current number to the sum variable using the compound assignment operator +=.

Once the loop is complete, we print out the value of sum to the console using string interpolation. The output should be The sum is: 15 for the given array of numbers.

gistlibby LogSnag