Map array of objects to Dictionary in Swift

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

    Since Swift 4 you can do @Tj3n's approach more cleanly and efficiently using the into version of reduce It gets rid of the temporary dictionary and the return value so it is faster and easier to read.

    Sample code setup:

    struct Person { 
        let name: String
        let position: Int
    }
    let myArray = [Person(name:"h", position: 0), Person(name:"b", position:4), Person(name:"c", position:2)]
    

    Into parameter is passed empty dictionary of result type:

    let myDict = myArray.reduce(into: [Int: String]()) {
        $0[$1.position] = $1.name
    }
    

    Directly returns a dictionary of the type passed in into:

    print(myDict) // [2: "c", 0: "h", 4: "b"]
    

提交回复
热议问题