Swift Language Dictionaries Accessing Values


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 = "Book 1"

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 bookNumbers in books.keys {
    print("Book number: \(bookNumber)")
// outputs:
// Book number: 1
// Book number: 2

To get all key and value pair corresponding to each other (you will not get in proper order since it is a Dictionary)

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

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

If you want to access multiple levels of a Dictionary use a repeated subscript syntax.

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

print(myDictionary["Toys"][2]) // Outputs "Truck"
print(myDictionary["Interests"][1]) // Outputs "Science"