Dictionary Creation in Swift

Level 3152 keystrokes

Creates a dictionary, adds a key with subscript assignment and loops over the key-value pairs. Dictionary order is not guaranteed, so the three lines may appear in a different order.

Swift code

// A var dictionary of type [String: Int], so entries can be added
1var scores = ["Alice": 95, "Bob": 87]
// Assigning to a new key adds it (an existing key would be updated)
2scores["Charlie"] = 92
3
// Each pair is split into name and score; the order may differ between runs
4for (name, score) in scores {
// Prints e.g. Alice: 95
5 print("\(name): \(score)")
6}
// count is the number of keys: Count: 3
7print("Count: \(scores.count)")

Output

Alice: 95
Bob: 87
Charlie: 92
Count: 3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 10
  • (× 6
  • )× 6
  • :× 4
  • \× 3
  • ,× 2
  • [× 2
  • ]× 2
  • =× 2
  • .× 1

More Swift examples at level 3

← Swift typing practice