What is array.max() in Swift?
Overview
The array.max() is used to get the largest element in an array.
Syntax
arr.max()
Parameters
The function takes no parameters.
Return value
It returns the largest element in the array. If the array has no elements, a nil is returned.
Example
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
Explanation
- Lines 2 to 5: We create three separate arrays.
- Lines 8 to 11: We invoke the
max()method on each of the arrays and the results are stored in separate variables. - Lines 14 to 17: We print the results to the console.
Note: For an empty array, the
max()function returns aniland 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.
Example
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!)
Explanation
-
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
keyvalue is40. -
Line 11: The result is printed.