Map array of objects to Dictionary in Swift

前端 未结 9 496
半阙折子戏
半阙折子戏 2021-01-30 00:32

I have an array of Person\'s objects:

class Person {
   let name:String
   let position:Int
}

and the array is:

         


        
9条回答
  •  伪装坚强ぢ
    2021-01-30 01:12

    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})
    

提交回复
热议问题