Swift Dictionary updateValue()

The updateValue() method updates the value in the dictionary for the given key.

Example


updateValue() Syntax

The syntax of the updateValue() method is:

dictionary.updateValue(new_value, forKey: key)

Here, dictionary is an object of the Dictionary class.


updateValue() Parameters

The updateValue() method takes one parameter:

  • new_value - the new value to add
  • key - the key whose value is to be updated.

Note: If the key doesn't already exist, the new key-value pair is created.


updateValue() Return Value

  • The updateValue() method returns the value that was replaced.

Note: The method returns nil if new key-value pair is added.


Example 1: Swift updateValue()

Output

Marks Before: ["Nick": 59, "Sabby": 78]
Marks After: ["Nick": 67, "Sabby": 78]

Example 2: Create new key-value Pair

Output

Before: ["Sabby": 78, "Nick": 59]
After: ["Sabby": 78, "Nick": 59, "Sazz": 45]

Here, since there is no key named "Sazz" in the marks dictionary, so the new key-value pair is created.