Swift - Convert Array to Dictionary

后端 未结 7 1546
轻奢々
轻奢々 2021-02-15 12:00

I just want convert an array of Player Names into a dictionary Scoreboard, giving everyone an initial score of 0.

Meaning...

var playerNames =          


        
7条回答
  •  梦如初夏
    2021-02-15 12:09

    You can use reduce(into:) as you suspected. You simply need to declare the initial value as [String:Int]() to be an empty Dictionary of the required type, then simply set the value of all keys in playerNames to 0.

    var playerNames = ["Harry", "Ron", "Hermione"]
    var scoreBoard = playerNames.reduce(into: [String:Int](), { currentScores,player in
        currentScores[player] = 0
    })
    

提交回复
热议问题