从Swift中的Dictionary中获取特定键的所有值

时间:2016-01-29 20:02:23

标签: ios arrays swift dictionary

我有一个像这样的字典数组。

let arr = [["EmpName"   :   "Alex",     "Designation"   :   "Jr. Developer"],
           ["EmpName"   :   "Bob",     "Designation"   :   "Sr. Developer"],
           ["EmpName"   :   "Claire",  "Designation"   :   "Jr. Developer"],
           ["EmpName"   :   "David",   "Designation"   :   "Project Manager"]]

现在我想从中获取EmpName个对象。我如何在swift中执行此操作?我基本上想要一个具有以下值的数组。

["Alex", "Bob", "Claire", "David"]

这就是我现在所做的。但是我想知道我是否可以通过使用filtermap ...

来做到这一点。
var employees = [String]()
    for empRecord in arr {
        employees.append(empRecord["EmpName"]!)
    }

2 个答案:

答案 0 :(得分:6)

一种简单的方法是使用flatMap

let employees = arr.flatMap { $0["EmpName"] }

结果:

  

[" Alex"," Bob"," Claire"," David"]

Swift中的

flatMap就像map,但它也安全地展开了选项,这是我们需要的,因为Swift词典总是返回Optionals。

答案 1 :(得分:1)

这有两种方法。如果你使用NSArray很酷,我就是这个解决方案的粉丝。

let arr = [["EmpName"   :   "Alex",     "Designation"   :   "Jr. Developer"],
    ["EmpName"   :   "Bob",     "Designation"   :   "Sr. Developer"],
    ["EmpName"   :   "Claire",  "Designation"   :   "Jr. Developer"],
    ["EmpName"   :   "David",   "Designation"   :   "Project Manager"]]

let names = arr.map { (dictionary) -> String? in
    return dictionary["EmpName"]
}
// names now contains array of names as String?

// If you want to use NSArray
let newArray = arr as NSArray
let newNames = newArray.valueForKeyPath("EmpName")

// newNames now contains array of names as String