Swift中的Float数组中的最大值和最小值

gpb*_*pbl 3 arrays swift

根据这个答案,为了获得阵列的最大值,我们可以做到:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })
Run Code Online (Sandbox Code Playgroud)

我们怎么能为a做同样的事情Array<Float>,因为没有minmaxfor Float

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 8

这里给出的解决方案/sf/answers/1691270311/适用于所有可比元素序列,因此也适用于浮点数组:

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let numMax = maxElement(floats)
Run Code Online (Sandbox Code Playgroud)

maxElement() 在Swift库中定义为

/// 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
Run Code Online (Sandbox Code Playgroud)


Ant*_*nio 6

只需使用第一个数组元素作为初始值:

let numMax = floats.reduce(floats[0], { max($0, $1) })
Run Code Online (Sandbox Code Playgroud)

但是当然你需要floats在做之前检查数组是否为空.