You can use the [minElement()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func-generator-element_-comparable-minelement>)
and [maxElement()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func-generator-element_-comparable-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)
As of Swift 3, the methods have been renamed to [min()](<http://swiftdoc.org/v3.0/protocol/Sequence/#func-iterator-element_-comparable-min>)
and [max()](<http://swiftdoc.org/v3.0/protocol/Sequence/#func-iterator-element_-comparable-max>)
respectively:
let minimumNumber = numbers.min() // Optional(1)
let maximumNumber = numbers.max() // 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 }