Sling Academy
Home/Swift/Swift: Access and Update Values in a Dictionary

Swift: Access and Update Values in a Dictionary

Last updated: May 08, 2023

Accessing values in a Swift dictionary

To access values in a Swift dictionary, you need to use the key as a subscript, such as dictionary[key]. This will return an optional value, which you can unwrap using if let or guard let statements.

Example:

let products = [
    "iPhone 14": 699.00,
    "iPhone 14 Pro": 999.00,
    "iPhone 14 Pro Max": 1099.00,
    "iPhone 15": 699.00,
]

let iPhone14Price = products["iPhone 14"]
if(iPhone14Price != nil) {
    print("The iPhone 14 costs \(iPhone14Price!)")
} else {
    print("The iPhone 14 is not available")
}

Output:

The iPhone 14 costs 699.0

If the value is a sub-dictionary or an array, you need to cast it to the appropriate type before accessing its elements.

Example:

let data: [String: Any] = ["name": "John", "scores": [10, 20, 30]]
if let scores = data["scores"] as? [Int] {
    print("The first score is \(scores[0])")
} else {
    print("There are no scores")
}

Output:

The first score is 10

Updating the value of a key in a dictionary

Using the updateValue(_:forKey:) method

When calling the updateValue(_:forKey:) method on a dictionary, it will return the old value if the key exists or nil if a new key-value pair is added.

Example:

var websites = [
    "www.slingacademy.com": "A place to learn programming",
    "api.slingacademy.com": "Public REST API for developers",
]

let oldValue = websites.updateValue(
    "A place to learn Swift",
    forKey: "www.slingacademy.com"
)

print(websites)

Output:

[
  "api.slingacademy.com": "Public REST API for developers", 
  "www.slingacademy.com": "A place to learn Swift"
]

Using the subscript syntax

The subscript syntax can be used to assign a new value to an existing key in a dictionary.

Example:

var websites = [
    "www.slingacademy.com": "A place to learn programming",
    "api.slingacademy.com": "Public REST API for developers",
]

websites["www.slingacademy.com"] = "A place to learn Swift"
print(websites)

Output:

[
  "www.slingacademy.com": "A place to learn Swift", 
  "api.slingacademy.com": "Public REST API for developers"
]

Next Article: Swift: Adding new key-value pairs to a dictionary

Previous Article: Swift: Counting Elements 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: Adding new key-value pairs to 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)