Swift - Convert Array to Dictionary

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

    reduce is definitely one of the more difficult builtin functions to use correctly, but it is what you want here.

    let names = ["Harry", "Ron", "Hermione"]
    let scoreboard: [String: Int] = names.reduce(into: [:], { result, next in
        result[next] = 0
    })
    

    It takes 2 parameters: the initial value (in our case, an empty dictionary [:]), and a closure that updates the result with each element in the array. This closure has 2 parameters, result and next. We want to update result based on the next element. Our closure does this by setting result[next] to 0.

提交回复
热议问题