Arun K Arun K - 1 year ago 99
Swift Question

How can i get top 2 max values from an array of float numbers in swift?

I need to get the 2 max value from an array of float number i.e. one highest and one second highest.Is there any simple way of getting the along with their indexes or do I need to change the array to structure for this?

Answer Source

Just sort the array and take the required value

var array1 = [2.1, 2.2, 2.5, 3.0, 4.2, 2]

var array2 = array1.sort(){ $0 > $1}

//One way 
let firstMax = array2[0]
let secondMax = array2[1]

//Second way
let firstMax = array2.removeFirst()
let secondMax = array2.removeFirst()


If you want the indexes just get them like

let maxPos = array1.indexOf(firstMax)
let secMaxPos = array1.indexOf(secondMax)

If you are confused with these things just follow the normal basics as follows.

var max = -1.0, maxPos = -1, secMax = -1.0, secMaxPos = -1
for (index, value) in array1.enumerate() {
    if value > max {
        max = value
        maxPos = index
    } else if value > secMax {
        secMax = value
        secMaxPos = index
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download