Swift – Find Minimum in Array

To find the minimum element of an Array in Swift, call min() method on this Array. Array.min() returns the minimum element by comparison.

We can also provide a predicate to min() method, by which the comparison happens between elements.

The following is a quick code snippet to find the minimum element of an Array array.

if let result = array.min() {
    //result holds the minimum value
} else {
    //array is empty. no minimum element.
}

Examples

In the following program, we take an array of numbers, and find the minimum element of this array using Array.min() method.

main.swift

let nums = [6, 8, 4, 2, 5]
if let result = nums.min() {
    print("Minimum element : \(result)")
} else {
    print("Array is empty. No minimum element.")
}

Output

Minimum element : 2
Program ended with exit code: 0

Now, let us take an array of strings, and find the minimum element. By default, comparison between two strings happen lexicographically, meaning, which ever comes first in a dictionary is the smallest.

main.swift

let names = ["apple", "banana", "mango", "fig", "cherry"]
if let result = names.min() {
    print("Minimum element : \(result)")
} else {
    print("Array is empty. No minimum element.")
}

Output

Minimum element : apple
Program ended with exit code: 0

We already mentioned that we can give a predicate to min() method. In the above program, let us provide a predicate to min() function such that min() returns a string with the smallest length.

main.swift

let names = ["apple", "banana", "mango", "fig", "cherry"]
if let result = names.min(by: {a, b in a.count < b.count}) {
    print("Minimum element : \(result)")
} else {
    print("Array is empty. No minimum element.")
}

Output

Minimum element : fig
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to find the minimum element of an Array in Swift programming.