1

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?

1
  • 1
    Why do you store a Double as a String? And what happens when the values are equal? Commented Apr 2, 2019 at 8:24

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

1

Use a comparator which is able to handle numeric strings

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.