To access an item in a dictionary using its subscript, specify its key:
var myTable = [ "Apple": "iOS", "Google" : "Android", "Microsoft" : "Windows Phone" ] var ranking = [/*from w ww.ja v a 2 s. 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:
var myTable = [ "Apple": "iOS", "Google" : "Android", "Microsoft" : "Windows Phone" ] let p = myTable["Apple"] if p != nil {//from w ww. j ava 2 s.com print(p!) //iOS } else { print("Key not found") }