Wednesday, January 2, 2019

swift - How do I sort an array of objects in reverse order efficiently?



Suppose I have an array of dictionaries:



[ { "id": 2 }, { "id": 59 }, { "id": 31 } ... ]



How can I sort this so that it's in descending order, sorted by "id"?



My initial approach is something like:



Loop through each element, find the biggest one, and put it into a new array. Then, remove that from the element. Repeat.


But I know that's wrong and not efficient.


Answer



You can use the sort function in Swift. Something like this:




let arr = [["id": 2], ["id": 59], ["id": 31]]
let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...