Search code examples
arraysswift

Find min / max value in Swift Array


Given an array of Swift numeric values, how can I find the minimum and maximum values?

I've so far got a simple (but potentially expensive) way:

var myMax = sort(myArray,>)[0]

And how I was taught to do it at school:

var myMax = 0
for i in 0..myArray.count {
    if (myArray[i] > myMax){myMax = myArray[i]}
}

Is there a better way to get the minimum or maximum value from an integer Array in Swift? Ideally something that's one line such as Ruby's .min and .max.


Solution

  • Given:

    let numbers = [1, 2, 3, 4, 5]
    

    Swift 3:

    numbers.min() // equals 1
    numbers.max() // equals 5
    

    Swift 2:

    numbers.minElement() // equals 1
    numbers.maxElement() // equals 5