根据这个答案,为了获得阵列的最大值,我们可以做到:
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>,因为没有min和maxfor Float?
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];
Run Code Online (Sandbox Code Playgroud)
这里给出的解决方案/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)
只需使用第一个数组元素作为初始值:
let numMax = floats.reduce(floats[0], { max($0, $1) })
Run Code Online (Sandbox Code Playgroud)
但是当然你需要floats在做之前检查数组是否为空.
| 归档时间: |
|
| 查看次数: |
6847 次 |
| 最近记录: |