如何通过快捷键将字典数组分组? [英] How to group Array of Dictionaries by a key in swift?

查看:44
本文介绍了如何通过快捷键将字典数组分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个字典数组

For example, I have this array of dictionaries

 [["Country":"Egypt","Name":"Mustafa","Age":"20"],["Country":"Palestine","Name":"Omar","Age":"15"],["Country":"Egypt","Name":"Ali","Age":"40"],["Country":"Jordan","Name":"Ahmad","Age":"25"],["Country":"Palestine","Name":"Amani","Age":"30"],["Country":"Jordan","Name":"Mustafa","Age":"20"]]

我想按国家/地区分组以成为

I want to group them by Country to become

  {"Egypt": [{"Country":"Egypt","Name":"Mustafa","Age":"20"} {"Country":"Egypt","Name":"Ali","Age":"40"}],
   "Palestine": [{"Country":"Palestine","Name":"Amani","Age":"30"},{"Country":"Palestine","Name":"Omar","Age":"15"}],
   "Jordan":[{"Country":"Jordan","Name":"Ahmad","Age":"25"},{"Country":"Jordan","Name":"Mustafa","Age":"20"}]
}

请帮助.

推荐答案

Swift具有出色的功能,可以为您完成此任务...

Swift has a nice function that does this for you...

let people = [["Country":"Egypt","Name":"Mustafa","Age":"20"],["Country":"Palestine","Name":"Omar","Age":"15"],["Country":"Egypt","Name":"Ali","Age":"40"],["Country":"Jordan","Name":"Ahmad","Age":"25"],["Country":"Palestine","Name":"Amani","Age":"30"],["Country":"Jordan","Name":"Mustafa","Age":"20"]]

let peopleByCountry = Dictionary(grouping: people, by: { $0["Country"]! } )

peopleByCountry 现在将成为您想要的格式.

peopleByCountry will now be the format that you want.

您可以在文档中了解更多信息.

只需添加Hamish的评论即可.

Just to add to Hamish's comment.

您真的不应该在这里使用字典".您应该使用Structs ...

You really shouldn't be working with Dictionaries here. You should be working with Structs...

struct Person {
    let countryName: String
    let name: String
    let age: Int
}

更好的是拥有一个 Country 结构...

Even better would be to have a Country struct...

struct Country {
    let name: String
}

,并在 Person 中将其用于其 country 属性,而不是 String .

and use that in the Person for their country property instead of String.

这篇关于如何通过快捷键将字典数组分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆