Related Tags

swift
communitycreator

# How can we get the minimum element of an array in Swift

Theodore Kelechukwu Onyejiaku

### Overview

The min() method can be used to get the minimum element of an array.

### Syntax

arr.min()


### Parameters

arr: This is the array whose minimum element we want to find.

### Return value

The value returned is the minimum element of the array. If the array has no element, a nil value is returned.

### Code example

// create arrays
let evenNumbers = [2, 10, 4, 12, 6, 8]
let negativeNumbers = [-1.3, -0.5, 0.002, 4.5]
let decimalNumbers = [45.7, 44.2, 90.0, 23.3]

// get minimum elements
let minEvenNo = evenNumbers.min()!
let minNegNo = negativeNumbers.min()!
let minDecNo = decimalNumbers.min()!

// print results
print(minEvenNo)
print(minNegNo)
print(minDecNo)
Get the minimum elements of arrays in Swift

### Code explanation

• Lines 2–4: We create some arrays.
• Lines 7–9: We invoke the min() method on the arrays we created. Then, we store the results in some variables.
• Lines 12–14: We print the results to the console.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time