Skip to main content

Map

A collection containing key-value pairs.

var phone_book: [String: String] = [
"Malcom": "012345",
"Jane": "789078",
]

Accessing Elements

Elements can be looked up using [key]. The result is always an optional element depending on whether the element was found in the map or not.

var janes_phone = phone_book["Jane"]
if janes_phone != nil {
print("Jane: \{janes_phone!}")
}
else {
print("Jane's is not in the phone book")
}

Updating Elements

To add or update an element's value assign a value.

phone_book["Jane"] = "657844"

Removing Elements

To remove an element assign nil to a certain key.

phone_book["Malcom"] = nil

Removing non existing elements is a no-op.

Iterating Elements

Maps can be iterated with the for statement.

caution

The order in which the elements are iterated is non-deterministic.

for name, phone in phone_book {
print("\{name}: \{phone}")
}

Printing

Maps can be interpolated into strings and print their contents.

caution

The order in which the elements are printed is non-deterministic.

print("\{phone_book}") // Prints [Malcom: 012345, Jane: 789078]

Supported Key Types

  • Int
  • String
  • Float
  • Bool

Properties

is_empty: Bool (get)

Whether the map contains no elements.

length: Int (get)

Number of elements in the map.

Methods

clear() -> ()

Removes all elements from the map.

copy() -> ([Key: Value])

Returns a copy of the map.

caution

This does not create copies of the values with reference semantics, e.g. classes, arrays, etc.