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
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"]