Dictionaries x Swift 3

I feel terrible for taking so long to post a new article and I am going to feel even more terrible because this story will be very very brief….BUT, I hope that it is informative…

I wanted to share some cool, possibly unknown, features about Dictionaries in Swift. So let’s dig right into it then :)

What are Dictionaries?

Think of them as literal dictionaries that you would use to find the meaning of the word.

Dictionaries store items in what we call key-value pairs. So in other words, the word you are looking up is the “key” and the definition of that word is the “value”…make sense? Cool, right let’s checkout some cool functionality.

A common place to use Dictionaries would be when using an API that passes you JSON objects, the JSON Serialiser would typically parse that data into Dictionaries that you can “query” to obtain say the value associated with the key of say a username.

Oh and one last thing…In a Dictionary, it’s values must be of the same type and it’s keys must be of the same type!

Initialising Dictionaries

Typically we would initialise a Dictionary like so:

var myNumberDictionary = [Int: String]()

Adding to Dictionaries

This is pretty darn simple in Swift, add a number like so:

myNumberDictionary = [3: "Three"]

Executing print(myNumberDictionary.count) would output 1. And executing print(myNumberDictionary[3]!) would output 3 to the console.

Note: Dictionaries cannot guarantee that they contain a certain value for a key or a certain key for a value. So they are Optionals. So you need to unwrap it, hence why I used the bang operator ! to unwrap the optional returned. Beware of using the bang operator, rule of thumb is to only use it when you know that the item you are unwrapping will never contain a nil.

Clearing the Dictionary

Even easier than creating one…Just use this nifty little : operator :

myNumberDictionary = [:]

Your Dictionary will now be clear ;)

Updating Values

Let’s say I have a Dictionary that contains a JSON object that has been parsed. In there I have a email key that has a String value attached to it representing an e-mail address for the user. But now we want to change it safely, you know….in case it is nil. It can easily and safely be done like this:

if let oldEmailAddress = myJSONDictionary.updateValue("newEmail@address.com", for key: "email") {
print(Old e-mail address \(oldEmailAddress) was replaced!)

The updateValue function updates the value for the supplied key and returns the previous value that you can use inside the if let statement. Cool hey?

Removing Values

Removing values can be done in different ways. A long and a short way.

The short way:

myJSONDictionary["email"] = nil

The long way:

if let removedValue = myJSONDictionary.removeValue(forKey: "email") {
print("E-mail address \(removedValue) has been removed!")

Notice how the long way allows you to use the removed value safely. If you need this functionality use the long way, but if you just want to remove then use the short way :)

Iterating Through Dictionaries The Cool Way

Imagine you want to run through the dictionary and for each item in the dictionary, you want to access both the key and the value? Well look no further…

for (myKey, myValue) in myDictionary {
print(My key is \(myKey) and it's value is \(myValue))

But wait…..I want to just iterate it by means of it’s values. NO PROBLEM!

for myValue in myDictionary.values {
print("My value is \(myValue)")

Oh and I am sure you guessed it….You can do the same with the keys ;)

for myKey in myDictionary.keys {
print(My key is \(myKey))

Arrays from Dictionaries — Hidden Gem

This is like a little hidden gem that can be very very useful sometimes. Imagine you want to make an array from a Dictionary. And you want one array to contain only the values and the other array to contain only the keys. Yes, Swift let’s you do that in one line…Can you believe it?! Haha

var myKeysArray = [Int](myNumberDictionary.keys)

var myValuesArray = [String](myNumberDictionary.values)

All you have to do is specify the type of the keys or the values using the []. Because remember, all keys in same Dictionary must be of same type and the same goes for values.

Final Comments

I know this wasn’t as innovative as testing a cool Framework but I thought it would be nice to share some syntax tips? Was I wrong in assuming this?

Let me know by commenting below :)

Recommend and Heart this story if you liked it! :)

Show your support

Clapping shows how much you appreciated Dino Alves’s story.