Map array of objects to Dictionary in Swift

前端 未结 9 507
半阙折子戏
半阙折子戏 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 00:59

    You may write custom initializer for Dictionary type, for example from tuples:

    extension Dictionary {
        public init(keyValuePairs: [(Key, Value)]) {
            self.init()
            for pair in keyValuePairs {
                self[pair.0] = pair.1
            }
        }
    }
    

    and then use map for your array of Person:

    var myDictionary = Dictionary(keyValuePairs: myArray.map{($0.position, $0.name)})
    

提交回复
热议问题