Start learning free

LESSON 237 OF 349 · HASH TABLE

Hash Maps in Swift in Swift

Lesson

Hash Tables, better known as Hash Maps, are just collections of key-value pairs. In other words, they are pieces of data (values) mapped to unique identifiers called properties (keys).

Hash Maps were designed to give us a way of, given a key, associating a value with it for very quick lookups.

In Swift, the Hash Map is implemented as a Dictionary


Creation:

You create an empty Hash Map by declaring a [keyType: valueType] dictionary, where the keyType and valueType are the data types of the keys and values.

Let's declare a Hash Map that maps text values represing digits to their numerical value (e.g. "two" => 2). We wil map strings to integers, so the two types are String and Int. We will name the map digitValue

var digitValue = [String: Int]()

Creating an empty dictionary takes O(1) time.


Initialization:

You can also add some key-value pairs in your dictionary at creation:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

Accessing values:

A value is retrieved from a map using the subscript [] operator:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

// Accesing values:
digitValue["zero"] // returns  0

digitValue["one"] //  returns 1

digitValue["three"] // returns nil since 'three' does not exist

digitValue["three", default: 0] // returns 0 as the default value

As you can see, if you refer to a key that is not in the map, Swift returns nil. We can use ?? defaultValue or [key, default: value] to specify a default value in case it does not exist

Accessing a value from a map takes O(1) time.


Adding an entry:

We can add a key / value pair by using the subscript assignment as follows:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

// Adding new entries:
digitValue["three"] = 3

//The new Hash Map:
// [
//  "zero": 0,
//  "one":  1,
//  "three": 3
// ]

Adding a new entry to a map takes O(1) time.


Updating an entry:

We can update an existing entry by using the subscript assignment as follows:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

// updating entries:
digitValue["zero"] = 5

//the new hash map:
// [
//  "zero": 5,
//  "one":  1
// ]

Updating an entry from a map takes O(1) time.


Deleting entries:

The removeValue(forKey:) method allows you to remove a key from a map:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

// removing entries:
digitValue.removeValue(forKey: "zero")

//the new hash map:
// [
//  "one":  1
// ]

If you try to delete a key that is not in the map, it won't do anything.

Deleting an entry from a map takes O(1) time.


Checking if a key exists:

You can check if a key exists in a map using the keys.contains() method:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]


digitValue.keys.contains("zero") // returns true since the key exists

digitValue.keys.contains("three") // returns false since the key does not exist

Checking if a key exists in the map is O(1) time.


Iterating over the map keys:

If we want to iterate over keys of the map, we can use the for loop along with the in keyword and the keys property as follows:

var digitValue: [String: Int] = [
    "zero": 0,
    "one": 1
]

for key in digitValue.keys {
    print("\(key) is \(digitValue[key]!)")
}

// This will print:
// one is 1
// zero is 0

Notice the order is not the same as initiated. Dictionary keeps the data in random order

Iterating over a dictionary takes O(n) time.



Assignment
Follow the Coding Tutorial and let's play with some dictionaries.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    Hash Map in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free