Swift Dictionaries

Swift Dictionaries

Dictionaries store key-value pairs.

Lookups are fast by key.

Use subscripting to read and write values.


Basics

Example

var ages: [String: Int] = ["Kai": 30]
ages["Elisabeth"] = 25
print(ages["Kai"] ?? 0)

This example adds and reads values using dictionary subscripting.



Iterate Keys and Values

Loop through a dictionary to access keys and values.

Example

let ages = ["Kai": 30, "Elisabeth": 25]
for k in ages.keys.sorted() {
  print("\(k): \(ages[k]!)")
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *