How can we get the minimum element of an array in Swift
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 arrayslet 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 elementslet minEvenNo = evenNumbers.min()!let minNegNo = negativeNumbers.min()!let minDecNo = decimalNumbers.min()!// print resultsprint(minEvenNo)print(minNegNo)print(minDecNo)
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.