Swift – Maximum Element of a Set

To find maximum element of a Set in Swift, call max() method on this Set. The method returns the element that is maximum in value.

Examples

In the following example, we take a Set nums and find the maximum element in this Set.

main.swift

</>
Copy
let nums: Set = [2, 4, 6, 18, 10]
if let m = nums.max() {
    print("Maximum Element : \(m)")
}

Output

Maximum Element : 18
Program ended with exit code: 0

Now, let us take a Set of Strings fruits, and find the maximum value.

main.swift

</>
Copy
let fruits: Set = ["banana", "mango", "apple"]
if let m = fruits.max() {
    print("Maximum Element : \(m)")
}

Output

Maximum Element : mango
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to find the maximum element in a Set using Set.max() method.