In iOS Swift, I am sorting an array in descending order as per the below code. The code works fine, however, 'Price' is not a double but a string (so currently the code makes some mistakes when it is multi-digit numbers).
How can I convert the string 'Price' into a double within this one-line sorting function?
OfferList.sort { $0.Price > $1.Price }
I know there are ways of doing it when writing the sort as a multi-line loop, but is there a way of doing it directly in the line above?
Double
has an initializer that can take a StringProtocol
, though of course it returns an Optional
since the string may or may not actually be numbers. In order to sort your strings as doubles you'll need a fallback option in case it fails, or else you'll need to force unwrap these init
s if you can guarantee they'll always be doubles. The options look like this:
//Fallback using a nil-coalescing operator
OfferList.sort { (Double($0.Price) ?? 0) > (Double($1.Price) ?? 0) }
//Force unwrapping
OfferList.sort { Double($0.Price)! > Double($1.Price)! }
As a small, unrelated aside, it is considered best practice to name variables and attributes of objects in camel case, like offerList
and $0.price
. Not a requirement, of course, but this is what other Swift developers would be expecting.