简体   繁体   English

如何根据键对数组进行排序?

[英]How to sort array based on key?

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? 我该怎么做呢?

You should experiment with sort function, it is very useful. 你应该试验sort函数,它非常有用。

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? awarded应该是一个Bool属性,而不是String ,对不对?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM