Swift Set max()

The max() method returns the maximum element in the set.


var numbers: Set = [9, 34, 11, -4, 27]

// find the largest number print(numbers.max()!)
// Output: 34

max() Syntax

The syntax of the set max() method is:


Here, set is an object of the Set class.

max() Parameters

The max() method doesn't take any parameters.

max() Return Values

  • returns the maximum element from the set

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 set max()

// create set of integers
var integers: Set = [2, 4, 6, 8, 10]

// create set of floating-point number
var decimals: Set = [1.2, 3.4, 7.5, 9.6]

// find the largest element in integers set print(integers.max())
// find the largest element in decimals set print(decimals.max()!)



In the above example, we have created two sets named integers and decimals. Notice the following:

  • integers.max() - since we have not unwrapped the optional, the method returns Optional(10)
  • decimals.max()! - since we have used ! to force unwrap the optional, the method returns 9.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()!)



Here, the elements in the languages set are strings, so the max() method returns the largest element (alphabetically).

Did you find this article helpful?