Swift - Convert Array to Dictionary

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

    Using reduce(into:_:):

    var playerNames = ["Harry", "Ron", "Hermione"]
    
    let playerScore = playerNames.reduce(into: [:]) { counts, playerNames in
        counts[playerNames, default: 0] += 0 
    }
    
    print(playerScore)
    

    To keep a count of the players names (eg. duplicate names):

    counts[myArray, default: 0] += 1
    

    So for example if Ron had two entries before the game started (score > 0) then you would know.

    Without using reduce(into:_:) method and as an extension:

    var playerNames = ["Harry", "Ron", "Hermione"]
    
    extension Sequence where Self.Iterator.Element: Hashable {
    
    func freq() -> [Self.Iterator.Element: Int] {
        return reduce([:]) {
                ( iter: [Self.Iterator.Element: Int], element) in
                var dict = iter
                dict[element] = 0
                return dict
            }
        }
    }
    
    print(playerNames.freq())
    // ["Harry": 0, "Hermione": 0, "Ron": 0]
    

    keep a count (eg. duplicate names):

    dict[element, default: -1 ] += 1
    

提交回复
热议问题