Swift Dictionary

Welcome to Swift Tutorial. In this tutorial, we will learn about Dictionaries in Swift, how to access them, modify, and iterate through the elements.

Following are some of the facts about Dictionaries in Swift.

  • A Swift Dictionary stores (key, value) pairs. There is no order in which these (key, value) pairs are stored.
  • You need to declare the datatype of key and value during Dictionary declaration. And there is strict check when you add an element to the Dictionary.
  • A key is always unique in a dictionary, while there is no constraint on the value.
  • You can merge multiple dictionaries into a single Dictionary.
  • You can create a dictionary from arrays. It takes two arrays to create a Dictionary. One array for keys and the other for values.
  • You can also convert a dictionary into arrays. All the keys into one array and the corresponding values into another array.
  • You may iterate through a dictionary using for loop.
Swift Dictionary

Following is an example Swift Dictionary with some initial values.

var myDict:[Int:String] = [22:"Swift Tutorial", 12:"Tutorial Kart"]

where

  • myDict is the identifier to the Dictionary.
  • Int in [Int:String] is the datatype of Keys.
  • String in [Int:String] is the datatype of Values.
  • On the right side of the assignment operator, it is an array of (key:value) pairs.

We shall learn about different topics of Swift Dictionary in detail in the following tutorials with lucid examples.

  1. Create a Swift Dictionary.
  2. Create a Swift Dictionary using Arrays.
  3. Iterate through a Swift Dictionary and access the (key, value) pairs.
  4. Get Swift Dictionary size.
  5. Check if Swift Dictionary is Empty.
  6. Add or append an element to a Swift Dictionary.
  7. Get value using a key from Swift Dictionary.
  8. Check if a key is present in the Swift Dictionary.
  9. Merge two Swift Dictionaries
  10. Convert a Swift Dictionary into Arrays of Keys and Values.
  11. Print all the keys in a Swift Dictionary