Swift Program to Replace Elements in a Dictionary


In Swift, a dictionary is an unordered collection of key-value pairs. So, to replace the value of a key Swift provides bracket notation or subscript notations. Using this notation we can also add new key-value pair in the dictionary if the specified pair does not exist.

Syntax

dict[keyName] = “Value”

Here, dict is the dictionary. The keyName represents the key whose value you want to replace, and the Value represent the new value.

Algorithm

  • Step 1 − Create a dictionary with key-value pairs.

  • Step 2 − Display the original dictionary.

  • Step 3 − Now replace the value of a key with the new value using the subscript notation.

  • Step 4 − Display the modified value.

Example

In the following Swift program, we are going to replace elements in a dictionary. So for that, we create a dictionary and then using subscript notation we replace the original value of the key: 105 with the new value that is “Puppy”.

import Foundation
import Glibc

var myPet = [102:"Cow", 103:"Dog", 104: "Cat", 105: "Lizard"]
print("Original Pet dictionary: \(myPet)")

myPet[105] = "Puppy"

print("Modified Pet dictionary: \(myPet)")

Output

Original Pet dictionary: [105: "Lizard", 102: "Cow", 104: "Cat", 103: "Dog"]
Modified Pet dictionary: [105: "Puppy", 102: "Cow", 104: "Cat", 103: "Dog"]

Conclusion

So this is how we can replace elements in a dictionary. Using bracket notation we can replace only one value at a time with the new value. Also, note that the order of the key-value pairs may vary because the dictionary is an unordered collection.

Updated on: 09-May-2023

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements