Swift: Updating Elements

Updating Elements of Swift’s Dictionary:

To ensure that our key-value pairs contain relevant information, we must occasionally update their elements. So, we update elements of dictionary in Swift.

If one of our contacts changes their phone number, for example, we can go into our settings and update it to reflect their new number.

We can’t change the name of our keys, but we can change the value that goes with them. We can change our values in Swift in a variety of ways.

To change a value, one option is to use subscript syntax:

nameofDictionary[Key] = NewValue

Assume we had a scores dictionary:

var scores = [
"Bob": 42,
"Alice": 10,
"Daisy": 33
];

Our code would look like this if we wanted to update the value associated with the key "Alice" using subscript syntax:

scores["Alice"] = 37;

We can also use the .updateValue() method to change our values:

nameofDictionary.updateValue(NewValue, forKey: Key)

The .updateValue() method can be called on a dictionary given two values. The first is the new value we’d like to link to the key. The second value begins with forKey: and is followed by the key whose value we want to change.

We could use this code to update "Alice" in scores using the .updateValue() method:

scores.updateValue(37, forKey: "Alice");

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: