For-in loop and why it stops

I’m new Swift. The below exercise is teaching me how to assign multiple return values to a function. But it’s the for-in loop that’s confusing me. When I learned about these, the exercises always looped through all the possibilities in the array and then every one was included in the output. Why doesn’t currentMax below get assigned every value in the array that is greater than its original value? It only gets assigned the maximum highest value. How does it know to only assign the highest value that meets the else if condition. I would have thought currentMax would end up being all the numbers > array[0], which in this case would be all the numbers > 1. Thanks in advance for any help.



func minMax(array: [Int]) -> (min: Int, max: Int) {

    var currentMin = array[0]

    var currentMax = array[0]

    for value in array[1..

        if value < currentMin {

            currentMin = value

        } else if value > currentMax {

            currentMax = value



    return (currentMin, currentMax)


let bounds = minMax(array: [1, 2, 3, 4, 5, 6, 7])

print(“min is (bounds.min) and max is (bounds.max)”)

// Prints "min is 1 and max is 7"

Powered by WPeMatico


You may also like...

Comments are closed.