Lapinou - 10 months ago 48

Swift Question

I'm reading an iBook about Swift 2.2, and in a sample code, there is this function:

`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

}

if value > currentMax {

currentMax = value

}

}

return (currentMin, currentMax)

}

let values = [21, 1, -4, 7, 2, 12, 88, 12021, 456]

let bounds = minMax(values)

I tried this piece of code but I don't understand how the for loop works here:

`for value in array[1..<array.count]`

Why don't write:

`for value in array`

The only thing I noticed is with:

`for value in array[1..<array.count]`

it's looping 2 times to find the min and max number.

But using

`for value in array`

Answer

The first two lines of the function are already reading the first element:

```
var currentMin = array[0]
var currentMax = array[0]
```

So, there's no need to check it again. `array[1..<array.count]`

returns all elements of the array **except** the first (notice that the range starts at `1`

instead of `0`

).