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"
]