In Swift, you access values in a Dictionary using subscript notation dict[key]:
var scores = [String: Int]()
scores["Alice"] = 95
scores["Bob"] = 87
let aliceScore = scores["Alice"]! // 95
let bobScore = scores["Bob"]! // 87
If the key doesn't exist, subscript access returns nil. Use the [key, default:] subscript to provide a fallback:
let score = scores["Diana", default: 0] // returns 0 if not found
Check if a key exists with optional binding:
if let score = scores["Alice"] {
print(score)
}
Assignment
Follow the Coding Tutorial and access Alice's score from scores!
Hint
Use scores["Alice"]! and assign it to aliceScore.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check