Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Swift Array max()
In this tutorial, we will learn about the Swift array max() method with the help of examples.
The max() method returns the maximum element in the array.
Example
var numbers = [9, 34, 11, -4, 27]
// find the largest number
print(numbers.max()!)
// Output: 34
max() Syntax
The syntax of the array max() method is:
array.max()
Here, array is an object of the Array class.
max() Parameters
The max() method doesn't take any parameters.
max() Return Values
- returns the maximum element from the array
Note: The max() method returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals.
Example 1: Swift Array max()
// create an array of integers
var integers = [2, 4, 6, 8, 10]
// create an array of floating-point number
var decimals = [1.2, 3.4, 7.5, 9.6]
// find the largest element in integers array
print(integers.max())
// find the largest element in decimals array
print(decimals.max()!)
Output
Optional(10) 9.6
In the above example, we have created two arrays named integers and decimals. Notice the following:
integers.max()- since we have not unwrapped the optional, the method returnsOptional(10)
decimals.max()!- since we have used!to force unwrap the optional, the method returns9.6.
To learn more about forced unwrapping, visit Optional Forced Unwrapping.
Example 2: Find Largest String Using max()
var languages = ["Swift", "Python", "Java"]
// find the largest string
print(languages.max()!)
Output
Swift
Here, the elements in the languages array are strings, so the max() method returns the largest element (alphabetically).