Member-only story

Dictionaries in Swift

Swathi Prasad
3 min readMay 6, 2019

In the last days, I have been learning and coding in Swift. Swift is a powerful and general-purpose language. As a seasoned Java developer, I can correlate some of the Swift’s concepts and it is easy to learn.

In this article, I would like to introduce and delve into dictionary in Swift. Dictionary is a container which stores key-value pairs. All the keys in the dictionary are of the same type and all the values are of the same type. The order in dictionary is not maintained. If you are a Java developer, you can correlate this to Hashtable which gives fast access to its entries.

Defining a Dictionary

Dictionary is nothing but a comma separated key-value pair and defining such a dictionary literal is simple. Let us see the following example:

let person = [“firstname”:”John”, “lastname”:”Doe”, “location”:”Texas”]

Here, notice that I have used the keyword let which creates immutable dictionary. To create a mutable dictionary, just use var keyword.

var person = [“firstname”:”John”, “lastname”:”Doe”, “location”:”Texas”]

In the above examples, the compiler automatically identifies the type of keys and values. In this case, it is string since we have used strings. Suppose, if we want to create an empty dictionary, we need to tell the compiler…

--

--

Swathi Prasad
Swathi Prasad

Written by Swathi Prasad

Software architect and developer living in Germany. Sharing my opinion and what I learn.

No responses yet