Swift Dictionary updateValue()

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

Example

// create a dictionary with two elements
var information = ["Charlie": 54, "Harvey": 34]

// update value of "Charlie" to 57 information.updateValue(57, forKey: "Charlie")
// print updated dictionary print(information) // Output: ["Charlie": 57, "Harvey": 34]

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()

// create a dictionary with two elements
var marks = ["Sabby": 78, "Nick": 59]

print("Marks Before:", marks)

// update value of "Nick" to 67 marks.updateValue(67, forKey: "Nick")
// print updated dictionary print("Marks After:", marks)

Output

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

Example 2: Create new key-value Pair

// create a dictionary with two elements
var marks = ["Sabby": 78, "Nick": 59]

print("Before:", marks)

// associate value 45 to new key Sazz marks.updateValue(45,forKey: "Sazz")
// print updated dictionary print("After:", marks)

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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges