Swift:使用高阶函数过滤字典数组

时间:2016-03-03 02:02:08

标签: swift generics swift2

我在数组中有以下对象:

let john = ["name": "John", "Age" : "10", "Gender" : "Male", "City" : "SF"]
let peter = ["name" : "peter", "Age" : "12", "Gender" : "Male", "City" : "NY"]
let mary = ["name" : "mary", "Age" : "14", "Gender" : "Female", "City" : "TX"]
let bob = ["name" : "bob", "Age" : "10", "Gender": "Male" , "City" : "FL"]

var objArray = [john, john, peter, john, peter, mary, mary, bob, john, mary, peter, mary]

objArray由(4)john,(3)peter,(4)mary,(1)bob

组成

如果我能得到如下的字典数组将是理想的:

[["qty": 4, "obj": john], 
 ["qty": 3, "obj": peter], 
 ["qty": 4, "obj": mary], 
 ["qty": 1, "obj": bob]]

我尝试过:

var copyOfObjArray = objArray
var newArray = [[:]]

for obj in objArray{    
    let name = obj["name"]
    let age = obj["age"]

    print(name)
    var i = 0

    for copiedObj in copyOfObjArray{
        if copiedObj["name"] == name && copiedObj["age"] == age {
            i++
        }
    }

    let newDict = ["qty" : i, "obj" : obj]
    //I am not sure how to remove all the objects that are similar
    let index = copyOfObjArray.indexesOf(obj)

    newArray.append(newDict)
}

问题:有没有更好的方法来实现这一点,使用高阶函数,使其变得简单?如果是这样,代码示例将很棒

1 个答案:

答案 0 :(得分:3)

您正在寻找NSCountedSet。这是一个单行:

let cs = NSCountedSet(array:objArray)

现在cs知道所有要知道的事情。现在形成你的结果字典是微不足道的(但实际上,我不明白为什么你甚至需要它; NSCountedSet cs 本身已经拥有信息):

let result = cs.map { ["qty": cs.countForObject($0), "obj": $0] }