In Swift, a Dictionary stores key-value pairs where each key maps to a value.
var scores: [String: Int] = [:]
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72
Use [String: Int] to declare a dictionary where keys are strings and values are integers. Use dict[key] = value to add entries:
var ages: [String: Int] = [:]
ages["Alice"] = 25
ages["Bob"] = 30
print(ages["Alice"]!) // 25
print(ages.count) // 2
Assignment
Follow the Coding Tutorial and create a Dictionary named scores with three student scores!
Hint
Declare var scores: [String: Int] = [:] then use scores[key] = value to add entries.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check