Swift - Convert Array to Dictionary

后端 未结 7 1512
轻奢々
轻奢々 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:28

    If the player names are known to be all different then you can do

    let playerNames = ["Harry", "Ron", "Hermione", "Ron"]
    
    var scoreBoard = Dictionary(uniqueKeysWithValues: zip(playerNames,
                                                          repeatElement(0, count: playerNames.count)))
    
    print(scoreBoard) // ["Harry": 0, "Ron": 0, "Hermione": 0]
    

    Here zip is used to create a sequence of player/score pairs, from which the dictionary is created.

    Remark: Originally I had used AnySequence { 0 } to generate the zeros. Using repeatElement() instead was suggested by Alexander and has the advantage that the correct required capacity is passed to the dictionary intializer.

提交回复
热议问题