I have a array of dictionary like this.
let arr = [["EmpName" : "Alex", "Designation" : "Jr. Developer"],
["EmpName" : "Bob", "Designation" : "Sr. Developer"],
["EmpName" : "Claire", "Designation" : "Jr. Developer"],
["EmpName" : "David", "Designation" : "Project Manager"]]
Now I want to fetch only the EmpName
objects from this. How do I do this in swift? I basically want an array which have the following values.
["Alex", "Bob", "Claire", "David"]
This is what I do now. But I wonder if I could do that in a single like by using filter
or map
...
var employees = [String]()
for empRecord in arr {
employees.append(empRecord["EmpName"]!)
}
A simple way is to use flatMap
:
let employees = arr.flatMap { $0["EmpName"] }
Result:
["Alex", "Bob", "Claire", "David"]
flatMap
in Swift is like map
but it also safely unwraps optionals, which is what we need here since Swift dictionaries always return Optionals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With