Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Dictionaries in Swift
Written by Team Kodeco

A dictionary is a collection of key-value pairs. In Swift, dictionaries are unordered collections and the keys must be unique. Dictionaries are useful for storing data when you need to look up a value based on its associated key.

Here’s an example of how to create and use a dictionary:

// create a dictionary of string keys and integer values
var ages = ["John": 25, "Jane": 30, "Bob": 40]

// add a key-value pair to the dictionary
ages["Tom"] = 35
print(ages) // ["Jane": 28, "Tom": 35, "John": 25, "Bob": 40]

// safely access a value in the dictionary
if let bobAge = ages["Bob"] {
  print(bobAge) // 40
}

// modify a value in the dictionary
ages["Jane"] = 28
print(ages) // ["Jane": 28, "Tom": 35, "John": 25, "Bob": 40]

When accessing a value by its key, it’s important to check whether the key exists in the dictionary before trying to access the value. The example above uses optional binding with if let to safely unwrap the optional before accessing it.

You can also create an empty dictionary using the [:] initializer:

var emptyDictionary: [String: Int] = [:]

It is important to note that dictionaries in Swift are value types, which means they are copied when they are passed as a function argument or assigned to a variable.

© 2024 Kodeco Inc.