I have an array of Person
\'s objects:
class Person {
let name:String
let position:Int
}
and the array is:
This is what I have been using
struct Person {
let name:String
let position:Int
}
let persons = [Person(name: "Franz", position: 1),
Person(name: "Heinz", position: 2),
Person(name: "Hans", position: 3)]
var peopleByPosition = [Int: Person]()
persons.forEach{peopleByPosition[$0.position] = $0}
Would be nice if there was a way to combine the last 2 lines so that peopleByPosition
could be a let
.
We could make an extension to Array that does that!
extension Array {
func mapToDict(by block: (Element) -> T ) -> [T: Element] where T: Hashable {
var map = [T: Element]()
self.forEach{ map[block($0)] = $0 }
return map
}
}
Then we can just do
let peopleByPosition = persons.mapToDict(by: {$0.position})