Swift Dictionary

Filed Under: Swift
swift dictionary

Swift Dictionary is one of the important collection types. Let’s get started by launching playground in XCode.

Swift Dictionary

swift dictionary

  • Swift Dictionary is a collection of key-value pair elements. They are unordered list of values of the same type with unique keys. Under the hood, they are just HashTable.
  • Hashtable is data structure composed of Arrays and a hash function, to say the least.
  • They are very useful when you need to search something from a large data. In such cases Arrays, LinkedList would consume more time typically with the complexity of O(N) or O(logN). This is where Hashtable are useful as they can return you the search result within O(1) time normally.
  • How are the books in your library arranged so that you can find your favorite book easily? How do you search a word in your dictionary? The answer is Hashtables. They use hash function to convert the data into a simpler one such that you can easily trace the value from the key.
  • Swift Dictionaries are value types. Not reference types.

Creating a dictionary

The following dictionary we initialize has the key of type String and value of type Int:


var countryCodes = [String: Int]()

countryCodes["India"] = 91
countryCodes["USA"] = 1

In the above code we initialise the dictionary in square brackets. The key is on the left of the colon and the value is on the right.

The above is the shorthand syntax. The full syntax of a dictionary is:


let dictionary:Dictionary<KeyType, ValueType> = [:]

Alternatively, we can define a dictionary like:


var secondDictionary = ["Swift" : "iOS", "Java" : "Android" , "Kotlin" : "Android"]

secondDictionary["Java"] //"Android"
secondDictionary["Kotlin"] //"Android"
secondDictionary["Java"] //nil

Swift infers the type of the Dictionary as <String, String>. If a key doesn’t exist, it returns a nil. To remove a key we just need to set the value to nil.

Swift Dictionary Properties and Functions

  • removeAll() method is used to clear the contents of a dictionary.
  • count property is used to get the number of key-value pairs.
  • isEmpty returns the boolean which tells whether the dictionary is empty or not.
  • first returns the first element(key/value pair of the dictionary).
  • removeValue(forKey: ) removes the value at the specified key. The value can be stored in a variable/constant.
  • We can call keys and values property on dictionary to get the array of keys and values respectively.

print(countryCodes) // ["India": 91, "USA": 1]
print(countryCodes.first) //prints Optional((key: "India", value: 91))
let returnedValue = countryCodes.removeValue(forKey: "USA")  // 1
countryCodes.removeAll()
countryCodes.count //0
countryCodes.isEmpty //true
print(countryCodes) //prints : [:]

var keysArray = Array(secondDictionary.keys)

Iterating over a Swift Dictionary

To iterate over a Dictionary in Swift, we use Tuple and a for-in loop.


for (key,value) in secondDictionary
{
    print("key is \(key) and value is \(value)")
}
//Prints

//key is Java and value is Android
//key is Kotlin and value is Android
//key is Swift and value is iOS

Since dictionaries are not ordered, you can’t predict the order of iteration.

Default Value for non-existing key

If the key doesn’t exist, instead of returning a nil, we can set a default value as shown below.


secondDictionary["Python", default: "No Value"] // "No Value"

Creating a Dictionary from two arrays

We’ve converted Swift Dictionary to Swift Arrays to get keys and values array.
Now let’s merge two arrays to create a dictionary.


let keys = ["August", "Feb", "March"]
let values = ["Leo", "Pisces", "Pisces"]
let zodiacDictionary = Dictionary(uniqueKeysWithValues: zip(keys,values))
print(zodiacDictionary)

zip creates a sequence of pairs built out of two underlying sequences.

Handling Duplicate Keys

What if we reverse the keys and values in the above code. It’ll have duplicate keys. Let’s look at how to handle duplicate keys using zip.


let zodiacs = ["Leo", "Pisces", "Pisces", "Aries"]
let repeatedKeysDict = Dictionary(zip(zodiacs, repeatElement(1, count: zodiacs.count)), uniquingKeysWith: +)
print(repeatedKeysDict) //["Leo": 1, "Pisces": 2, "Aries": 1]

The dictionary is of the type [String:Int]
The value for each key is incremented if there are repeatable elements with the default value set to 1.

The above code indirectly gets the number of occurrences of each word.

Dictionary Filtering and Mapping

Swift 4 has given rise to filtering and mapping functions on a Dictionary as shown below.


let filtered = repeatedKeysDict.filter { $0.value == 1 }
print(filtered) //prints ["Leo": 1, "Aries": 1]

let mapped = filtered.mapValues{"Occurence is \($0)"}
print(mapped) //prints ["Leo": "Occurence is 1", "Aries": "Occurence is 1"]

$0.values gets the current value in filter.
$0 gets the current value in mapValues

This brings an end to this tutorial.

References : Apple Docs

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages