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.
This tutorial is about finding maximum and minimum numbers from an array of numbers in swift for example.
max
and min
functionsmax
and min
functionsThere are multiple ways we can find max and min in swift.
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
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)
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts