Sling Academy
Home/Swift/Swift: Adding new key-value pairs to a dictionary

Swift: Adding new key-value pairs to a dictionary

Last updated: May 08, 2023

There are two ways to add new key values to a given dictionary in Swift. Let’s explore them in this concise example-based article.

Using the subscript syntax

You can use the subscript syntax to add a new key-value pair to a dictionary:

// this dictionary stores the products and their prices
var products = [String: Int]()

products["computer"] = 1000
products["mouse"] = 25

print(products)

Output:

["computer": 1000, "mouse": 25]

If you use the subscript syntax with a key that already exists, its value will be updated.

Using the updateValue(_:forKey:) method

The name of this method contains the word “update,” but it can still be used to add a new key-value pair to a dictionary. The method returns the old value if the key exists or nil if a new key-value pair is added.

Example:

var animals = ["cat": "meow", "dog": "woof"]
if let oldValue = animals.updateValue("moo", forKey: "cow") {
    print("The old value of \(oldValue) was replaced with a new one.")
} else {
    print("A new key-value pair was added to the dictionary.")
    print(animals)
}

Output:

A new key-value pair was added to the dictionary.
["cat": "meow", "cow": "moo", "dog": "woof"]

Next Article: Swift: Removing a key-value pair from a dictionary

Previous Article: Swift: Access and Update Values in a Dictionary

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array