Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch all values for a particular key from a Dictionary in Swift

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"]!)
    }
like image 297
Ramaraj T Avatar asked Mar 13 '23 11:03

Ramaraj T


1 Answers

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.

like image 158
Eric Aya Avatar answered Apr 09 '23 12:04

Eric Aya