Swift - 来自2个过滤数组的字典

时间:2017-07-17 14:15:12

标签: arrays swift dictionary

idsArr = [ ["id": "12345"], ["id": "27891"],["id": "98654"] ]
idsNameIntvalueArr = [["id": "22913", "name" : "Peter Parker", "value": 15], ["id": "12345", "name" : "Donald Duck", "value": 6],  ["id": "98654", "name" : "Mickey Mouse", "value": 9], ["id": "112233", "name" : "Lion King", "value": 9]]

我是Swift的新手,请给我建议,用id比较这两个数组的最佳做法是什么,如果id匹配,如何在内部使用字典获取数组,结果如下:

resultArr = [["Donald Duck": 6],["Mickey Mouse": 9]] 

甚至更好的只是字典,如果可能的话:

resultdict = ["Donald Duck": 6, "Mickey Mouse": 9]

感谢。

1 个答案:

答案 0 :(得分:4)

Swift 3.x

let idsArr = [ ["id": "12345"], ["id": "27891"],["id": "98654"] ]
let idsNameIntvalueArr = [["id": "22913", "name" : "Peter Parker", "value": 15], ["id": "12345", "name" : "Donald Duck", "value": 6],  ["id": "98654", "name" : "Mickey Mouse", "value": 9], ["id": "112233", "name" : "Lion King", "value": 9]]

var result = [String:Int]()

idsNameIntvalueArr.forEach({ name in
  idsArr.forEach({
    if name["id"] as? String == $0["id"] { result[name["name"] as! String ] = name["value"] as? Int }
  })
})
print(result)

将返回:

["Mickey Mouse": 9, "Donald Duck": 6]