Swiftly

Swift 5.7 references for busy coders

Dictionaries

Dictionaries store associations between keys of the same type and values of the same type in a collection with no defined ordering. Example:

let pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
let nicknamePerPlayer = ["Rashida": "Ida", "Isabella": "Isa", "Tomoko": "Ko"]

Mutability

Dictionaries defined with var are mutable:

var pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
pointsPerPlayer["Louis"] = 85
pointsPerPlayer["Rashida"] = nil
print(pointsPerPlayer) // ["Isabella": 275, "Louis": 85, "Tomoko": 115]

Type

The type of a dictionary can be determined without type annotations:

let pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115] // Inferred to be type [String: Int]
let nicknamePerPlayer = ["Rashida": "Ida", "Isabella": "Isa", "Tomoko": "Ko"] // Inferred to be [String : String]

But the type can also be explicitly declared:

let pointsPerPlayer: [String: Int] = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
let nicknamePerPlayer: [String: String] = ["Rashida": "Ida", "Isabella": "Isa", "Tomoko": "Ko"]

Empty dictionaries

An empty dictionary must be defined with a type:

var pointsPerPlayer: [String: Int] = [:]
print(pointsPerPlayer) // [:]

Alternatively, initializer syntax may be used:

var pointsPerPlayer = [String: Int]()
print(pointsPerPlayer) // [:]

A dictionary can be emptied after creation:

var pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
pointsPerPlayer = [:]
print(pointsPerPlayer) // [:]

Iterating over dictionaries

A dictionary may be interated over using for-in.

var pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
for (player, points) in pointsPerPlayer {
  print("\(player) has \(points) points.")
}
// Output:
// Tomoko has 115 points.
// Rashida has 150 points.
// Isabella has 275 points.

count and isEmpty

count returns the number of elements in the dictionary. isEmpty can be used to determine if the dictionary has no elements.

var pointsPerPlayer = ["Rashida": 150, "Isabella": 275, "Tomoko": 115]
print(pointsPerPlayer.count) // 3
print(pointsPerPlayer.isEmpty) // false
pointsPerPlayer = [:]
print(pointsPerPlayer.count) // 0
print(pointsPerPlayer.isEmpty) // true

See also

Further reading