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:
us
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"]
Use a comparator which is able to handle numeric strings
users.sort { $0.weekFTC.compare($1.weekFTC, options: .numeric) == .orderedDescending }