Map array of objects to Dictionary in Swift

前端 未结 9 516
半阙折子戏
半阙折子戏 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:02

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

提交回复
热议问题