简体   繁体   中英

how to get number of maximum element in array in swift

How to solve it? I should get 2 in this case.

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

ps: new quality standarts when posting - is something crazy...

This is how I would go about doing it:

let array = [1, 3, 5]

if let (maxIndex, maxValue) = array.enumerated().max(by: { $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.")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM