Swift: Different ways to find the Min/Max of an array

Updated: May 5, 2023 By: Khue Post a comment

This concise and straight-to-the-point article shows you a couple of different ways to find the minimum and maximum elements of a given array in Swift. Without any more delays, let’s begin.

Using the built-in min() and max() methods

The Array class provides two methods min() and max(). These methods return the minimum and maximum elements of the array, respectively, if the element type conforms to the Comparable protocol.

Example:

let numbers = [2, 6, 1, 25, 13, 7, 9]
let minimumNumber = numbers.min() 
let maximumNumber = numbers.max() 

print("The minimum number is \(minimumNumber!)")
print("The maximum number is \(maximumNumber!)")

Output:

The minimum number is 1
The maximum number is 25

Using the reduce() method

This method takes an initial value and a closure that combines each element of the array with the previous result and returns the final result. We can make use of it to find the min and max of a given numeric array like so:

let numbers = [2, 6, 1, 25, 13, 7, 9]
let minValue = numbers.reduce(Int.max) { min($0, $1) } 
let maxValue = numbers.reduce(Int.min) { max($0, $1) } 

print("minValue: \(minValue)")
print("maxValue: \(maxValue)")

Output:

minValue: 1
maxValue: 25

In this example, you can notice the appearance of the min() and max() functions. They are global numeric functions that return the minimum and maximum of two comparable values, respectively:

let a = 3
let b = 5
let c = min(a, b) 
// c == 3

let d = max(a, b) 
// d == 5

Using a for loop

You can use a for-in loop to iterate over the array and compare each element with a variable that stores the current minimum or maximum value.

Example:

let numbers = [2, 6, 1, 25, 13, 7, 9]
var minimumNumber = Int.max
var maximumNumber = Int.min
for number in numbers {
    if number < minimumNumber {
        minimumNumber = number
    }
    if number > maximumNumber {
        maximumNumber = number
    }
}

print("The minimum number is \(minimumNumber)")
print("The maximum number is \(maximumNumber)")

Output:

The minimum number is 1
The maximum number is 25