Map array of objects to Dictionary in Swift

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

    You can use a reduce function. First I've created a designated initializer for Person class

    class Person {
      var name:String
      var position:Int
    
      init(_ n: String,_ p: Int) {
        name = n
        position = p
      }
    }
    

    Later, I've initialized an Array of values

    let myArray = [Person("Bill",1), 
                   Person("Steve", 2), 
                   Person("Woz", 3)]
    

    And finally, the dictionary variable has the result:

    let dictionary = myArray.reduce([Int: Person]()){
      (total, person) in
      var totalMutable = total
      totalMutable.updateValue(person, forKey: total.count)
      return totalMutable
    }
    

提交回复
热议问题