如何用swift中的键对字典数组进行分组?

时间:2018-04-09 09:42:19

标签: arrays swift dictionary

例如,我有这个词典数组

 [["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"]]

我想按国家/地区对它们进行分组以成为

  {"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"}]
}

请帮忙。

3 个答案:

答案 0 :(得分:4)

Swift有一个很好的功能,可以帮到你......

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现在将成为您想要的格式。

您可以阅读有关此功能的更多信息in the documentation

只是为了添加Hamish的评论。

你真的不应该在这里使用词典。你应该使用Structs ......

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

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

struct Country {
    let name: String
}

并在Person中使用country属性代替String

答案 1 :(得分:0)

let arrCountry: [[String:String]] = [["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"]]

func sortCountry() {
    var sortedCountries : [String : [[String:String]]] = [:]
    for object in arrCountry {
        let country = object["Country"] as! String
        if var arrCountry = sortedCountries[country] {
            arrCountry.append(object)
            sortedCountries[country] =  arrCountry
        }
        else {
            sortedCountries[country] =  [object]
        }
    }
}

答案 2 :(得分:-1)

好吧,我会这样:

  1. 通过遍历数组获取所有国家/地区并将其存储在数组中。
  2. 这一系列国家的循环。
  3. 使用谓词筛选数组,其中country是当前国家/地区。
  4. 将其存储在最终的国家词典中。