Maps in Swift

To understand how to handle maps in Swift, we’ll look at how to create, update, and utilize them. Here’s a complete example using Swift.

import Foundation

// Swift’s built-in map type is called `Dictionary`.

func main() {
    // To create an empty dictionary, use the Dictionary initializer.
    var m: [String: Int] = [:]

    // Set key/value pairs using typical `name[key] = val` syntax.
    m["k1"] = 7
    m["k2"] = 13

    // Printing a dictionary will show all of its key/value pairs.
    print("map:", m)

    // Get a value for a key with `name[key]`.
    let v1 = m["k1"]
    print("v1:", v1 ?? 0)

    // If the key doesn’t exist, the nil-coalescing operator (`??`) can provide a default value.
    let v3 = m["k3", default: 0]
    print("v3:", v3)

    // The `count` property returns the number of key/value pairs in the dictionary.
    print("len:", m.count)

    // The `removeValue(forKey:)` function removes key/value pairs from a dictionary.
    m.removeValue(forKey: "k2")
    print("map:", m)

    // To remove all key/value pairs from a dictionary, use `removeAll()`.
    m.removeAll()
    print("map:", m)

    // The optional second return value when getting a value from a dictionary 
    // indicates if the key was present in the dictionary.
    let prs = m["k2"] != nil
    print("prs:", prs)

    // You can also declare and initialize a new dictionary in the same line with this syntax.
    let n: [String: Int] = ["foo": 1, "bar": 2]
    print("map:", n)

    // Dictionaries have a built-in equality check by default.
    let n2: [String: Int] = ["foo": 1, "bar": 2]
    if n == n2 {
        print("n == n2")
    }
}

// Running the main function
main()

To run the program, just place the code in a Swift file and use swift to execute it.

$ swift maps.swift
map: ["k1": 7, "k2": 13]
v1: Optional(7)
v3: 0
len: 2
map: ["k1": 7]
map: [:]
prs: false
map: ["foo": 1, "bar": 2]
n == n2

Now that we’ve covered basic operations with dictionaries in Swift, let’s continue to learn more about the language.