I have an array of Person
\'s objects:
class Person {
let name:String
let position:Int
}
and the array is:
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.