Swift Program to Update value of Dictionary using key


Swift provides a method named as updateValue() method to update the value of the dictionary using a specified key. If the specified key does not exist, then this method will add that key along with its value in the dictionary.

Syntax

dict.updateValue(nvalue, forKey: nkey)

Here, nvalue represents the new value and nkey represents the key to which we want to update or add value. If the given key exists in the dictionary, then its value is replaced by the new value. If the given key does not exist, then it will add the nkey and nvalue in the dictionary.

Algorithm

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

  • Step 2 − Print the original dictionary.

  • Step 3 − Update the value of a key with the new value using the updateValue() function.

  • Step 4 − Print the updated dictionary.

Example

In the following Swift program, we will update the value of the dictionary using a key. So first we will create a dictionary with some key-value pairs. Then we use the updateValue() method to update the value of key = 4 with the new value that is “aeroplane”. If the key does not exist, then it will add key-value pair as a new element in the dictionary. Finally, display the updated dictionary.

import Foundation
import Glibc

// Creating a dictionary
var dict = [3: "car", 4: "bike", 19: "bus", 2: "train"]

print("Original Dictionary:", dict)

// Update a key-Value pair
dict.updateValue("aeroplane", forKey: 4)

// Displaying output
print("Updated Dictionary:", dict)

Output

Original Dictionary: [2: "train", 19: "bus", 3: "car", 4: "bike"]
Updated Dictionary: [2: "train", 19: "bus", 3: "car", 4: "aeroplane"]

Conclusion

So this is how we can update the value of the dictionary using the key. The updateValue() method updates one value at a time. This function modifies the original dictionary. And return nil if the new key-value pair was added. Also, it updates the value of one key at a time.

Updated on: 10-May-2023

698 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements