Swift - Retrieving Elements from a Dictionary

Introduction

To access an item in a dictionary using its subscript, specify its key:

Demo

var myTable = [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

var ranking = [//w w  w.j a va 2s  . c o  m
     1: "Gold",
     2: "Silver",
     3: "Bronze"
]

print(myTable["Apple"])     //Optional("iOS")
print(ranking[2])             //Optional("Silver")

Because it is possible that the specified key might not exist in the dictionary, the returning result is an optional value of the dictionary's value type.

It is String? in the first example and Int? in the second.

You should check whether the value exists before proceeding to work with it:

Demo

var myTable = [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

let p = myTable["Apple"]
if p != nil {/*from ww w .  jav  a 2  s.  c  o  m*/
    print(p!)   //iOS
} else {
    print("Key not found")
}

Result

Related Topic