{

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.

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 The min 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)
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.