To iterate over a dictionary of dictionaries in Swift, you can use nested `for` loops to iterate through both the outer dictionary and the inner dictionaries. This allows you to access and process each key-value pair in the nested dictionaries.
We can iterate over a dictionary of dictionaries in Swift using nested `for` loops. This example demonstrates how to declare and initialize a dictionary of dictionaries, use nested `for` loops to iterate through the outer and inner dictionaries, and print each key-value pair.
For example,
outerDict
with string keys and integer values.var outerDict: [String: [String: Int]] = [
"A": ["X": 1, "Y": 2],
"B": ["Z": 3]
]
// Iterate over the dictionary of dictionaries using nested for loops
print("Iterating over dictionary of dictionaries:")
for (outerKey, innerDict) in outerDict {
print("Outer Key: \(outerKey)")
for (innerKey, value) in innerDict {
print(" Inner Key: \(innerKey), Value: \(value)")
}
}
Iterating over dictionary of dictionaries: Outer Key: A Inner Key: X, Value: 1 Inner Key: Y, Value: 2 Outer Key: B Inner Key: Z, Value: 3
We can iterate over a dynamically created dictionary of dictionaries in Swift using nested `for` loops. This example demonstrates how to declare a dictionary of dictionaries, add inner dictionaries dynamically, add key-value pairs to the inner dictionaries, use nested `for` loops to iterate through the outer and inner dictionaries, and print each key-value pair.
For example,
outerDict
.var outerDict: [String: [String: Int]] = [:]
// Add inner dictionaries dynamically
outerDict["A"] = [:]
outerDict["B"] = [:]
// Add key-value pairs to the inner dictionaries
outerDict["A"]?["X"] = 1
outerDict["A"]?["Y"] = 2
outerDict["B"]?["Z"] = 3
// Iterate over the dictionary of dictionaries using nested for loops
print("Iterating over dictionary of dictionaries:")
for (outerKey, innerDict) in outerDict {
print("Outer Key: \(outerKey)")
for (innerKey, value) in innerDict {
print(" Inner Key: \(innerKey), Value: \(value)")
}
}
Iterating over dictionary of dictionaries: Outer Key: A Inner Key: X, Value: 1 Inner Key: Y, Value: 2 Outer Key: B Inner Key: Z, Value: 3
In this tutorial, we learned How to Iterate Over a Dictionary of Dictionaries in Swift language with well detailed examples.