Swift – Get Value in Dictionary using Key
Welcome to Swift Tutorial. In this tutorial, we will learn how to get the value from a dictionary using a key in Swift programming.
A Swift dictionary stores each value under a unique key. Use the dictionary subscript syntax with that key to look up its associated value.
Swift Dictionary Value Lookup Syntax
To get the value using a key from a Swift Dictionary, use the following syntax.
var value = myDictionary[key]
The syntax is similar to accessing a value from an array using the index. Here, in case of the dictionary, key is playing the role of an index,
However, a dictionary key is not a numeric position. It is an identifier whose type must conform to Hashable, such as String, Int, or UUID.
Why Swift Dictionary Lookup Returns an Optional
A dictionary lookup returns an optional value because the requested key may not exist. For example, looking up a value in a [String: Int] dictionary produces an Int?, not a plain Int.
let marks = ["Mohan": 75, "Raghu": 82]
let existingValue = marks["Mohan"]
let missingValue = marks["John"]
print(existingValue as Any)
print(missingValue as Any)
Output
Optional(75)
nil
Because the result is optional, unwrap it safely before using it. Force unwrapping with ! is suitable only when the program can guarantee that the key exists. Otherwise, a missing key causes a runtime error.
Example 1 – Get Value in Dictionary using Key
In this example, we shall create a dictionary with initial values, and access the values from this dictionary using keys.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var mohanScore = myDictionary["Mohan"]
print("value is: \(mohanScore!)")
Output
value is: 75
The key "Mohan" is present in the dictionary, so the optional contains 75. The example force-unwraps that optional when printing it.
Example 2 – Get Value in Dictionary using Key
In this example, we shall create a dictionary of type [String, String], and access the values from this dictionary using keys.
main.swift
var myDictionary:[String:String] = ["Mohan":"Running", "Raghu":"Long Jump", "John":"High Jump"]
var johnActivity = myDictionary["John"]
print("value is: \(johnActivity!)")
Output
value is: High Jump
The dictionary has String keys and String values. Looking up "John" returns an optional containing "High Jump".
Safely Get a Swift Dictionary Value with if let
Use optional binding with if let when the key may be absent. The first branch runs when the value exists, and the else branch handles a missing key.
let marks = ["Mohan": 75, "Raghu": 82, "John": 79]
if let score = marks["Raghu"] {
print("Raghu's score is \(score)")
} else {
print("No score was found for Raghu")
}
Output
Raghu's score is 82
This approach avoids force unwrapping and makes the missing-key behavior explicit.
Get a Swift Dictionary Value with a Default
Use the default: dictionary subscript when the program should substitute a fallback value for a missing key.
let marks = ["Mohan": 75, "Raghu": 82]
let mohanScore = marks["Mohan", default: 0]
let johnScore = marks["John", default: 0]
print(mohanScore)
print(johnScore)
Output
75
0
The default value is returned only when the requested key is not present. Reading with this subscript does not insert the missing key into a dictionary declared with let.
Use guard let for a Required Dictionary Key
Inside a function, use guard let when the remaining code requires the dictionary value. It handles the missing-key case early and leaves the unwrapped value available afterward.
func printActivity(for name: String, activities: [String: String]) {
guard let activity = activities[name] else {
print("No activity found for \(name)")
return
}
print("\(name): \(activity)")
}
let activities = [
"Mohan": "Running",
"Raghu": "Long Jump",
"John": "High Jump"
]
printActivity(for: "John", activities: activities)
Output
John: High Jump
Distinguish a Missing Key from an Optional Dictionary Value
When the dictionary itself stores optional values, a subscript lookup can produce a nested optional. In such cases, use keys.contains(_:) when the program must distinguish between a missing key and a key whose stored value is nil.
let nicknames: [String: String?] = [
"Mohan": "Mo",
"Raghu": nil
]
print(nicknames.keys.contains("Raghu"))
print(nicknames.keys.contains("John"))
Output
true
false
Access Swift Dictionary Keys, Values, and Key-Value Pairs
Use the keys and values properties when the program needs all keys or all values. Iterate over the dictionary when both parts of every entry are required.
let marks = ["Mohan": 75, "Raghu": 82, "John": 79]
for name in marks.keys.sorted() {
print(name)
}
for (name, score) in marks.sorted(by: { $0.key < $1.key }) {
print("\(name): \(score)")
}
Output
John
Mohan
Raghu
John: 79
Mohan: 75
Raghu: 82
The example sorts the entries before printing because a dictionary should not be treated as a collection whose values are retrieved by a stable numeric position.
Find a Swift Dictionary Key for a Known Value
Dictionaries are designed for key-to-value lookup. When you only know a value, search the entries with first(where:). This operation scans the dictionary rather than performing a direct lookup.
let marks = ["Mohan": 75, "Raghu": 82, "John": 79]
if let entry = marks.first(where: { $0.value == 82 }) {
print(entry.key)
}
Output
Raghu
If multiple keys contain the same value, first(where:) returns only one matching entry. Use filter when all matching keys are needed.
Swift Dictionary Value Lookup Methods
| Requirement | Recommended Swift syntax |
|---|---|
| Return an optional value | dictionary[key] |
| Run code only when the key exists | if let value = dictionary[key] |
| Exit early when a required key is missing | guard let value = dictionary[key] else { ... } |
| Use a fallback for a missing key | dictionary[key, default: fallback] |
| Check whether a key is present | dictionary.keys.contains(key) |
| Find a key from a known value | dictionary.first(where: { $0.value == value }) |
Swift Dictionary Key Lookup FAQs
How do I get a value for a key in a Swift dictionary?
Use subscript syntax such as dictionary[key]. The result is optional because the dictionary may not contain that key.
Why does a Swift dictionary return an optional value?
The key may be absent, so Swift represents the result with an optional. A matching key produces a value, while a missing key produces nil.
How can I get a dictionary value without force unwrapping?
Use if let, guard let, nil coalescing with ??, or the default: dictionary subscript. Choose the method according to how the missing-key case should be handled.
Can I get a Swift dictionary value by numeric index?
A dictionary is intended for lookup by key, not by a stable numeric position. Convert or sort its entries when an ordered representation is required, but continue to use keys for direct value retrieval.
How do I find a dictionary key from its value in Swift?
Use first(where:) to find one matching key-value pair, or filter to collect all entries whose values match. This requires scanning the dictionary.
Swift Dictionary Lookup QA Checklist
- Confirm that the lookup uses the dictionary’s actual key type.
- Handle the optional result when the key is not guaranteed to exist.
- Avoid force unwrapping unless the key’s presence is enforced by program logic.
- Use a meaningful default value rather than hiding an unexpected missing key.
- Do not describe dictionary keys as stable numeric indexes.
- Sort dictionary entries when examples require predictable printed output.
- Use
first(where:)orfilteronly when reverse lookup by value is genuinely required.
Swift Dictionary Value Lookup Summary
In this Swift Tutorial, we have learned to access values using keys from a Swift Dictionary with the help of examples. We also covered optional results, safe unwrapping, default values, key existence checks, iteration, and finding a key from a known value.
TutorialKart.com