Start learning free

LESSON 126 OF 678 · DICTIONARIES

Accessing Dictionary Values in Swift

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check