2017-06-18 39 views
1

如何解决?在这种情况下,我应该得到2。如何在swift中获取数组中最大元素的个数

var r = [1, 3, 5] 
r.max() // gives 5 

PS:新的质量standarts时发布 - 是一些疯狂...

+0

我不明白。这是因为1和5吗? –

+0

@AaronZheng他希望得到索引 – Alexander

+0

可能重复[有效算法的最大值及其在Swift数组中的索引](https://stackoverflow.com/questions/42128950/efficient-algorithm-for-maximum-value-and - 它的折射率合迅速阵列)。 –

回答

1

这是我怎么会去这样做:

let array = [1, 3, 5] 

if let (maxIndex, maxValue) = array.enumerated.max{ $0.element < $1.element } { 
    print("The max element is \(maxValue) at index \(maxIndex)") 
} 
else { 
    print("The array is empty, and has no max element or index.") 
} 
相关问题