3

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) })

How can we do the same for an Array<Float>, since there's no min and max for Float?

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];
Community
  • 1
  • 1
gpbl
  • 4,721
  • 5
  • 31
  • 45

6 Answers6

8

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
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
6

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.

Antonio
  • 71,651
  • 11
  • 148
  • 165
3

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.

codester
  • 36,891
  • 10
  • 74
  • 72
2

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.

NFarrell
  • 255
  • 1
  • 17
1

Swift 2:

var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
let maxValue = graphPoints.maxElement()
William Hu
  • 15,423
  • 11
  • 100
  • 121
0

Tested in Swift >= 5.0

let numbers = [12.9, 2.7, 3.7, 4, 5, 4, 12.8]
print(numbers.max() ?? 0) // Output 12.9
print(numbers.min() ?? 0) // Output 2.7
emraz
  • 1,563
  • 20
  • 28