According to this answer, to obtain the maximum of an array we can do:
let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })
Swift 2:
var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
let maxValue = graphPoints.maxElement()
Just use the first array element as the initial value:
let numMax = floats.reduce(floats[0], { max($0, $1) })
but of course you need to check that the floats
array is not empty before doing it.
The solution given here https://stackoverflow.com/a/24161004/1187415 works for for all sequences of comparable elements, therefore also for an array of floats:
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let numMax = maxElement(floats)
maxElement()
is defined in the Swift library as
/// Returns the maximum element in `elements`. Requires:
/// `elements` is non-empty. O(countElements(elements))
func maxElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element
You can use -FLT_MAX
which returns minimum magnitude of Float
and used for same purpose
let numMax = floats.reduce(-FLT_MAX, { max($0, $1) })
For Double
array you can use -DBL_MAX
If you want maximum magnitude value of Float
use FLT_MAX
.FLT_MIN
is Minimum representable postive floating-point number.
Swift 4 has a .max()
method for Array<Float>
.
Example:
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let max = floats.max()
Note: max()
returns an optional so there's a chance it could come back nil.