Map array of objects to Dictionary in Swift

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

    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.

提交回复
热议问题