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..<array.count] {
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"
"currentMin" and "currentMax" are simple Int variables, not arrays, so the last assignment to each of them "wins".
BTW, you have a small bug in this code. If it is ever passed an empty array, your function will crash. You can avoid this by putting in a guard as the first line of your function:
func minMax(array: [Int]) -> (min: Int, max: Int) {
guard array.count > 0 else { return (0, 0) }
…However, returning min and max of 0 for an empty array may be a bug in itself, depending on what the calling code expects.
It's just one of those "edge cases" that you have to keep in mind when designing your code.