Swift – Get Value in Dictionary using Key

Welcome to Swift Tutorial. In this tutorial, we will learn how to get the value from a dictionary using a key in Swift programming.

To get the value using a key from a Swift Dictionary, use the following syntax.

var value = myDictionary[key]

The syntax is similar to accessing a value from an array using the index. Here, in case of the dictionary, key is playing the role of an index,

Example 1 – Get Value in Dictionary using Key

In this example, we shall create a dictionary with initial values, and access the values from this dictionary using keys.

main.swift

var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]

var mohanScore = myDictionary["Mohan"]

print("value is: \(mohanScore!)")

Output

value is: 75
ADVERTISEMENT

Example 2 – Get Value in Dictionary using Key

In this example, we shall create a dictionary of type [String, String], and access the values from this dictionary using keys.

main.swift

var myDictionary:[String:String] = ["Mohan":"Running", "Raghu":"Long Jump", "John":"High Jump"]

var johnActivity = myDictionary["John"]

print("value is: \(johnActivity!)")

Output

value is: High Jump

Conclusion

In this Swift Tutorial, we have learned to access values using keys from a Swift Dictionary with the help of examples.