Swift Array min()

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

Example


min() Syntax

The syntax of the array min() method is:

array.min()

Here, array is an object of the Array class.


min() Parameters

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


min() Return Values

  • returns the minimum element from the array

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 Array min()

Output

Optional(2)
1.2

In the above example, we have created two arrays 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()

Output

Java

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