Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
swift
hashmap

What are dictionaries in Swift?

Mohammad Razi ul Haq

A dictionary is a data container that holds key-value pairs in an unordered manner. These keys, and their corresponding values, can all only be of one type. Each value has to be associated with a keyacts as an identifier to access the data.

Declaring a dictionary

While declaring a dictionary, it is optional to give data types for the key value pairs as Swift can infer these data types if we do not supply them during the declaration. An empty dictionary is declared by specifying the key (value data type inside square brackets []).

import Swift

// initializing an empty dictionary
let firstDict:[Int:String] = [:]
print(firstDict)

// initializing a dictionary and letting swift infer data type
let secondDict = ["a":1, "b":2, "c":3, ]
print(secondDict)

// initializing a dictionary and giving the data types for the key-value pairs
var thirdDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
print(thirdDict)

Accessing and modifying data in a dictionary

The easiest and most common way to access an element in a dictionary is to use the key as a subscript. Swift also:

  • allows us to print our own message if a key is not present in the dictionary.
  • modify a value stored against a key using the updateValue function or equating a new value to the subscript.

The code used to do this is shown below:

import Swift

// accessing the values
var myDict:[String:Int] = ["a":1, "b":2, "c":3, "d":4, ]
print(myDict["a"]!)
print(myDict["c"]!)

// accessing keys not available in the dictionary
if let myVal = myDict["h"] {
    print("The value is \(myVal).")
} else {
    print("The value is not present against the key")
}

// modifying the values
var o = myDict.updateValue(24, forKey: "c")
print("Modified value for the key 'c'")
print(myDict["c"]!)

print("Modified value for the key 'c'")
myDict["c"] = 56
print(myDict["c"]!)

Iterating over keys and values in a dictionary

The code below shows how to iterate over key-value pairs in Swift:

import Swift

// accessing the values
var myDict = ["a":1, "b":2, "c":3, "d":4, ]
for (k, v) in myDict {
    print("The key '\(k)' holds the value '\(v)'.")
}

RELATED TAGS

communitycreator
swift
hashmap

CONTRIBUTOR

Mohammad Razi ul Haq
RELATED COURSES

View all Courses

Keep Exploring