Zana Zana - 7 months ago 10
Swift Question

How can I find the 3 highest elements of an Array using 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 = [4, 2, 14, 8, 12 ,10, 8]
let result = myArray.sort().suffix(3)
print(result)  // [10, 12, 14]
Comments