Swift – Find Maximum in Array

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

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

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

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

Examples

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

main.swift

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

Output

Maximum element : 8
Program ended with exit code: 0

Now, let us take an array of strings, and find the maximum 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.max() {
    print("Maximum element : \(result)")
} else {
    print("Array is empty. No maximum element.")
}

Output

Maximum element : mango
Program ended with exit code: 0

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

main.swift

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

Output

Maximum element : banana
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

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