Map array of objects to Dictionary in Swift
I have an array of Person
's objects:
class Person {
let name:String
let position:Int
}
and the array is:
let myArray = [p1,p1,p3]
I want to map myArray
to be a Dictionary of [position:name]
the classic solution is:
var myDictionary = [Int:String]()
for person in myArray {
myDictionary[person.position] = person.name
}
is there any elegant way by Swift to do that with the functional approach map
, flatMap
... or other modern Swift style
Solution 1:
Since Swift 4
you can do @Tj3n's approach more cleanly and efficiently using the into
version of reduce
It gets rid of the temporary dictionary and the return value so it is faster and easier to read.
Sample code setup:
struct Person {
let name: String
let position: Int
}
let myArray = [Person(name:"h", position: 0), Person(name:"b", position:4), Person(name:"c", position:2)]
Into
parameter is passed empty dictionary of result type:
let myDict = myArray.reduce(into: [Int: String]()) {
$0[$1.position] = $1.name
}
Directly returns a dictionary of the type passed in into
:
print(myDict) // [2: "c", 0: "h", 4: "b"]
Solution 2:
Okay map
is not a good example of this, because its just same as looping, you can use reduce
instead, it took each of your object to combine and turn into single value:
let myDictionary = myArray.reduce([Int: String]()) { (dict, person) -> [Int: String] in
var dict = dict
dict[person.position] = person.name
return dict
}
//[2: "b", 3: "c", 1: "a"]
In Swift 4 or higher please use the below answer for clearer syntax.