Start learning free

LESSON 102 OF 349 · DICTIONARIES

Accessing Dictionary Values in Swift 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

    Accessing Dictionary Values in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free