Start learning free

LESSON 103 OF 349 · DICTIONARIES

Updating Dictionary Values in Swift in Swift

Lesson

In Swift, you update a value in a Dictionary by using subscript notation — it overwrites the old value:

var scores = [String: Int]()
scores["Alice"] = 95
scores["Bob"] = 87

scores["Alice"] = 99  // update: Alice is now 99
scores["Charlie"] = 72 // add new entry

Subscript notation is used for both inserting and updating. You can also use updateValue(_:forKey:) to update a value and retrieve the previous one:

scores.updateValue(99, forKey: "Alice")  // updates Alice and returns old value

Assignment
Follow the Coding Tutorial and update Alice's score to 99!


Hint
Use scores["Alice"] = 99.

STEP 1 OF 1
    Ctrl + Enter to check

    Updating 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