Accessing Values

suggest change

A value in a Dictionary can be accessed using its key:

var books: [Int: String] = [1: "Book 1", 2: "Book 2"]
let bookName = books[1]
// bookName == Optional("Book 1"); a dictionary subscript returns an optional

The values of a dictionary can be iterated through using the values property:

for book in books.values {
    print("Book Title: \(book)")
}
//output: Book Title: Book 2
//output: Book Title: Book 1

Similarly, the keys of a dictionary can be iterated through using its keys property:

for bookNumber in books.keys {
    print("Book number: \(bookNumber)")
}
// outputs:
// Book number: 1
// Book number: 2

To visit each key together with its value (a dictionary does not promise order):

for (book, bookNumbers) in books {
    print("\(book)  \(bookNumbers)")
}
// outputs:
// 2  Book 2
// 1  Book 1

Note that a Dictionary, unlike an Array, is inherently unordered—that is, there is no guarantee on the order during iteration.

To read a nested dictionary, repeat the subscript. Each lookup returns an optional, so chain with ?.

// Create a multilevel dictionary.
var myDictionary: [String:[Int:String]]! = ["Toys":[1:"Car",2:"Truck"],"Interests":[1:"Science",2:"Math"]]

print(myDictionary["Toys"]?[2] as Any) // Optional("Truck")
print(myDictionary["Interests"]?[1] as Any) // Optional("Science")

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents