The array.max()
is used to get the largest element in an array.
arr.max()
The function takes no parameters.
It returns the largest element in the array. If the array has no elements, a nil
is returned.
Let’s look at the code below:
// creating arrayslet evenNumbers = [2, 10, 4, 12, 6, 8]let negativeNumbers = [-1.3, -0.5, 0.002, 4.5]let decimalNumbers = [45.7, 44.2, 90.0, 23.3]let emptyArray = [Int]() //empty array// getting maximum elementslet maxEvenNo = evenNumbers.max()!let maxNegNo = negativeNumbers.max()!let maxDecNo = decimalNumbers.max()!let emptyElement = emptyArray.max()// printing resultsprint(maxEvenNo) // 12print(maxNegNo) // 4.5print(maxDecNo) // 90.0print(emptyElement) // nil
max()
method on each of the arrays and the results are stored in separate variables.Note: For an empty array, the
max()
function returns anil
and throws an error.
max(by:)
max(by:)
method is similar to the max()
method. The only difference is that it finds the maximum element based on a predicate or a condition.
Let’s look at the code example:
// create a sequencelet ages = ["Mark" : 15, "John" : 20, "Jane" : 40]// get maximum element using max(by:)let keyMaxElement = ages.max(by: {$0 > $1})// print resultprint(keyMaxElement!)
Line 2: We create a sequence with the name ages
.
Lines 6 to 7: We write a predicate to get the maximum element greater than all other elements. Here, the greatest key
value is 40
.
Line 11: The result is printed.