Khledon
Khledon

Reputation: 183

Swift sorting array of structs by string double

I have an array of structs that I am looking to sort from highest to lowest based on Double value stored as a String. This is the way I'm currently doing it:

users.sort { (lhs, rhs) in return lhs.weekFTC > rhs.weekFTC }

This is returning the order based on the first number rather than the full number. Is there a better way of accomplishing this?

Upvotes: 1

Views: 252

Answers (2)

staticVoidMan
staticVoidMan

Reputation: 20234

You can convert the weekFTC string to a Double and then compare, like so:

users.sort { (lhs, rhs) -> Bool in
    let lhsVal = Double(lhs.weekFTC) ?? 0
    let rhsVal = Double(rhs.weekFTC) ?? 0

    return lhsVal > rhsVal
}

Comparing strings directly does a lexicographical comparison.

Example:

var array = ["111", "e3", "22"]

array.sort { (lhs, rhs) -> Bool in
    return lhs > rhs
}
print(array) //["e3", "22", "111"]

So we should see if the string can be made into a number and then sort.
This time it will do a numeric comparison, like so:

var array = ["111", "e3", "22"]

array.sort { (lhs, rhs) -> Bool in
    let lhs = Double(lhs) ?? 0
    let rhs = Double(rhs) ?? 0
    return lhs > rhs
}
print(array) //["111", "22", "e3"]

Upvotes: 2

vadian
vadian

Reputation: 285079

Use a comparator which is able to handle numeric strings

users.sort { $0.weekFTC.compare($1.weekFTC, options: .numeric) == .orderedDescending }

Upvotes: 1

Related Questions