Zana Zana - 7 months ago 16
Swift Question

How can I find the highest elements of an Array in Swift?

Can someone please explain how one would get the highest elements of an array in Swift 2.2?

For example lets say I have this code:

let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]


How would i retrieve the 3 highest values of that array?
In this case I'd want the numbers 6, 7 and 11.

Any help would be greatly appreciated.

Answer

Sort the array and take the last 3 items:

let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]
let highest3 = myArray.sort().suffix(3)
print(highest3)  // [6, 7, 11]
Comments