jimbeeer jimbeeer - 4 months ago 7
Swift Question

displaying aray output within repeat loop in swift

I'm working on an exercise in Swift 3 Playground.

I have an array called sums with a bunch of numbers in. I want to cycle through each of the array items and print 'The sum is: x' but I'm getting a generic error with the print command.

var i = 0
repeat {
print ("the sum is: \(sums[i])")
i = i + 1
} while i <= sums.count


Does anyone know what I'm doing wrong?

It must be done in a repeat loop as that's what the exercise is asking for.

Answer

sums.count will give you the size of the array. Arrays are 0-indexed in Swift. You're accessing out of the array range. Check for sums.count - 1 or:

var i = 0
repeat {
    print ("the sum is: \(sums[i])")
    i = i + 1
} while i < sums.count