Sorting Array of Dictionaries with Exceptions?

I have an array of dictionaries. And I need to sort this array in an ascending order.

someArray = someArray.sorted { lValue, rValue in lValue.categoryName < rValue.categoryName }

So one of the dictionaries is categoryName. Now, I have a case where the category name of an array element is something specific, say 'price,' then that element must be listed at the end as an exception to the rule above. Is that possible? Thanks.

Answered by Tomato in 729440022

I've used a custom sorting method with enum in reference to a topic at stack overflow.. (the one written by Martin R...)

This should be possible by adjusting your sort condition. Instead of lValue.categoryName < rValue.categoryNameyou could write something like this:

(lValue.categoryName == price || rValue.categoryName == price) || lValue.categoryName < rValue.categoryName

or

!(lValue.categoryName == price || rValue.categoryName == price) || lValue.categoryName < rValue.categoryName

This is not correct code yet and I didn't validate the conditions, but I hope you get the idea.

lValue.categoryName < rValue.categoryName is the sort condition the .sort-function uses to decide in which order the elements should appear. You can use very complex conditions or even a function deciding the order of two items by returning true or false depending on the order you want the two compared elements to appear.

Accepted Answer

I've used a custom sorting method with enum in reference to a topic at stack overflow.. (the one written by Martin R...)

Sorting Array of Dictionaries with Exceptions?
 
 
Q