Find maximum and minimum elements in an array in Swift with example| Dictionary
This tutorial is about finding maximum and minimum numbers from an array of numbers in Swift for example.
- Maximum and minimum elements of an array using
max
andmin
functions - Maximum and minimum elements of a dictionary using
max
andmin
functions
How to find maximum and minimum numbers in an array of numbers in swift
There are multiple ways we can find max and min in Swift.
- Use Array max, min method Array provides the
max
method that returns the maximum element from an array Themin
method returns the minimum element from an array.
Here is an example
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
let maxNum=numbers.max();
print((maxNum ?? 0))
let minNum=numbers.min();
print((minNum ?? 0))
Output:
9
1
How to find maximum and minimum from the Swift dictionary
The dictionary contains keys and values.
The following example contains employee names and salaries
This finds the maximum and minimum salaries of a dictionary in swift
let employees = ["John" : 5000, "Franc" : 2000, "Andrew" : 9000]
let maxSalary = employees.max { a, b in a.value < b.value }
print((maxSalary ?? 0))
let minSalary = employees.min { a, b in a.value < b.value }
print((minSalary ?? 0))
Output:
(key: "Andrew", value: 9000)
(key: "Franc", value: 2000)