TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift Array of Dictionary Elements

Create an array of dictionaries. Use an if-statement to test for an element with the dictionaries.
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.ArrayDictionary
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.
An example. 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.

If: We use the if-statement to test whether keys exist in the nested dictionaries. The string "cat" exists, but "diamond" does not.

If
Swift program that creates array of dictionaries // 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") } Output 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf