You can use the minElement()
and maxElement()
methods to find the minimum or maximum element in a given sequence. For example, with an array of numbers:
let numbers = [2, 6, 1, 25, 13, 7, 9]
let minimumNumber = numbers.minElement() // Optional(1)
let maximumNumber = numbers.maxElement() // Optional(25)
The returned values from these methods are Optional to reflect the fact that the array could be empty – if it is, nil
will be returned.
Note: The above methods require the elements to conform to the
Comparable
protocol.
You may also use the above methods with a custom closure, defining whether one element should be ordered before another, allowing you to find the minimum or maximum element in an array where the elements aren't necessarily Comparable
.
For example, with an array of vectors:
struct Vector2 {
let dx : Double
let dy : Double
var magnitude : Double {return sqrt(dx*dx+dy*dy)}
}
let vectors = [Vector2(dx: 3, dy: 2), Vector2(dx: 1, dy: 1), Vector2(dx: 2, dy: 2)]
// Vector2(dx: 1.0, dy: 1.0)
let lowestMagnitudeVec2 = vectors.minElement { $0.magnitude < $1.magnitude }
// Vector2(dx: 3.0, dy: 2.0)
let highestMagnitudeVec2 = vectors.maxElement { $0.magnitude < $1.magnitude }
let lowestMagnitudeVec2 = vectors.min { $0.magnitude < $1.magnitude }
let highestMagnitudeVec2 = vectors.max { $0.magnitude < $1.magnitude }