Iterating through dictionaries

The for-in loop also works when you want to iterate over a dictionary. But since the items in a dictionary are pairs, you need to use a tuple:

for (player, score) in namesAndScores { print("(player) - (score)")

}

// > Craig - 8

// > Anna - 2

// > Donna - 6

// > Brian - 2

It’s also possible to iterate over just the keys:

for player in namesAndScores.keys { print("(player), ", terminator: "") // no newline

}

print("") // print one final newline

// > Craig, Anna, Donna, Brian,

You can iterate over just the values in the same manner with the values property of the dictionary.

results matching ""

    No results matching ""