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.

About Dictionary

The following are some of the points to remember about Dictionaries in Swift.

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

The following picture depicts the elements in a Dictionary, which are key-value pairs.

Swift Dictionary

Example

The following is an example Swift Dictionary with some initial values.

</>
Copy
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.

Swift Dictionary Tutorials

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

Conclusion

In this Swift Tutorial, we learned about Dictionaries in Swift programming.