Swift Set min()

In this tutorial, we will learn about the Swift set min() method with the help of examples.

The min() method returns the minimum element in the set.


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

// find the smallest number print(numbers.min()!)
// Output: -4

min() Syntax

The syntax of the set min() method is:


Here, set is an object of the Set class.

min() Parameters

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

min() Return Values

  • returns the minimum element from the set

Note: The min() 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 min()

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

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

// find the smallest element in integers set print(integers.min())
// find the smallest element in decimals set print(decimals.min()!)



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

  • integers.min() - since we have not unwrapped the optional, the method returns Optional(2)
  • decimals.min()! - since we have used ! to force unwrap the optional, the method returns 1.2.

To learn more about forced unwrapping, visit Optional Forced Unwrapping.

Example 2: Find Smallest String Using min()

var languages: Set = ["Swift", "Python", "Java"]

// find the smallest string print(languages.min()!)



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

Did you find this article helpful?