3

I have an array which has two types of objects: Awarded and non-awarded. I simply want to sort my array so that awarded objects are placed first, and the rest are placed afterwards.

Here is the code that defines the key "awarded":

if let awarded = achievements[indexPath.row].userRelation["awarded"] as? String where awarded != "<null>" { }

Within those brackets I'd like to use my unwrapped value "awarded" to sort through the achievements and add those to the beginning, and the rest at the end.

How would I go about doing that?

3
  • What exactly is an achievement here? Is it an object, which contains a userRelation dictionary <String, String>? Kind of a strange entity model :/ Commented Oct 20, 2016 at 20:49
  • yeah it contains a bunch of properties, one of which is userRelation which has the "awarded" key Commented Oct 20, 2016 at 20:50
  • var descriptor = NSSortDescriptor(key: "awarded", ascending: false) var stories = (achievements as NSArray).sortedArray(usingDescriptors: [descriptor]) Commented Oct 21, 2016 at 5:40

1 Answer 1

2

You should experiment with sort function, it is very useful.

let sortedAchievements = achievements.sorted{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }

To sort in place use this:

achievements.sort{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }

I would recommend to refactor your model. It's better to use objects or structs instead of dictionaries. Also awarded should be a Bool property, not a String, right?

Sign up to request clarification or add additional context in comments.

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.