Home
Swift
Array of Dictionary Elements
Updated Aug 23, 2023
Dot Net Perls
Array of dictionaries. An array (in Swift 4) can have any element type. With dictionary elements, we create a collection of lookup tables. We build a complex, nested data structure.
Array
Dictionary
Nested square brackets. An array of dictionaries has syntax similar to a 2D array. We specify the dictionary type within an array type. The syntax might be confusing at first.
This example creates an array of String, Int dictionaries. It starts as an empty array. Then we add two dictionaries to it. We initialize them and append() them to the array.
Detail We use the if-statement to test whether keys exist in the nested dictionaries. The string "cat" exists, but "diamond" does not.
if
// This is an array of dictionaries. var dictionaries = [[String: Int]]() // Create a dictionary and add it to the array. var dictionary1: [String: Int] = ["cat": 100] dictionaries.append(dictionary1) // Create another dictionary. var dictionary2: [String: Int] = ["dog": 200] dictionaries.append(dictionary2) // Get value from dictionary in array element 0. if let value = dictionaries[0]["cat"] { print(value) } // Get value from dictionary that does not exist. if let value = dictionaries[1]["diamond"] { // This is not reached. print("Not reached") }
100
Some considerations. Swift supports classes. Sometimes using complex nested data structures (like arrays of dictionaries) becomes more complex and harder to maintain than arrays of classes.
class
A summary. We use nested square brackets to create 2D arrays and arrays of dictionaries in Swift. This syntax is clear and readable, but we must type the correct number of square brackets.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen