How to update elements in a dictionary in Swift?

In this article, I show you how you can update the elements in a dictionary in 2 different ways:

  1. With “subscript syntax”
  2. with the “updateValue” method
  3. or using a loop

Given is the following dictionary:

var myDict = ["apple": 10, "banana": 20, "orange": 30]

The subscript syntax

myDict["apple"] = 15 

print(myDict)

// Output: ["apple": 15, "banana": 20, "orange": 30]
  • In this example, we update the value for the “apple” key by assigning a new value to it using the subscript syntax.

The “updateValue(_:forKey:)” method

myDict.updateValue(15, forKey: "apple") 

print(myDict)

// Output: ["apple": 15, "banana": 20, "orange": 30]
  • In this example, we update the value for the “apple” key using the `updateValue(_:forKey:)` method.

Using a loop

for (key, value) in myDict {
  if key == "apple" {
    myDict[key] = 15
  }
}

print(myDict)

// Output: ["apple": 10, "banana": 20, "orange": 30]
  • In this example, we update the value for the “apple” key by iterating over the dictionary using a loop, checking for the key we want to update, and updating it when we find it.

Quick notes

  • A loop can be used to update elements in a dictionary in Swift when you want to update multiple elements in the dictionary based on certain conditions.
  • One common use case for this is when you want to update all the values in the dictionary that meet a certain criteria.
  • Regardless of the method you use, updating elements in a dictionary is a common operation in Swift when working with data.

Leave a Reply

Your email address will not be published. Required fields are marked *