Learn

Sometimes we need to update the values of our key-value pairs to ensure they contain relevant information.

For example, if one of our contacts changes their phone number, we can go into our settings and update it to contain their new phone information.

While we can’t change the name-value of our keys, we can change the value associated with them. With Swift, there are several ways we can change our values.

One option is to use subscript syntax to modify a value:

dictionaryName[Key] = NewValue

Suppose we had a dictionary called musicGenre:

var musicGenre = [ "Duke Ellington": "Jazz", "Taylor Swift": "Country", "David Bowie": "Rock" ]

If we wanted to update the value associated with the key "Taylor Swift" using subscript syntax, our code would look like this:

musicGenre["Taylor Swift"] = "Pop"

We also have the option of changing our values using the .updateValue() method:

dictionaryName.updateValue(NewValue, forKey: Key)

The .updateValue() can be called on a dictionary and given two values. The first is the new value we want to associate with the key. The second value starts with forKey: followed by the key we are changing the value of.

If we used the .updateValue() method to modify "Taylor Swift" in musicGenre, we could use this code:

musicGenre.updateValue("Pop", forKey: "Taylor Swift")

Instructions

1.

Take a look at the dictionary abbreviations in Abbreviations.swift.

Modify the value paired with the key "LOL" to be the correct term "Laugh Out Loud" using subscript syntax.

After clicking Run, check out the output terminal to see how the value changed!

2.

Use the .updateValue() method to change the value associated with the key "BRB" to "Be Right Back".

After clicking Run, check out the output terminal to see how the value changed!

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Already have an account?