find the value associated with a key in a map in swift

To retrieve the value associated with a key in a map (also known as a dictionary), follow these steps:

  1. Define a map
main.swift
var myMap = ["key1": "value1", "key2": "value2", "key3": "value3"]
67 chars
2 lines
  1. Use the key to access the corresponding value using subscript notation (square brackets)
main.swift
let value = myMap["key2"] // returns "value2"
46 chars
2 lines
  1. Check if the key exists in the map before accessing its value, to avoid a crash if the key does not exist
main.swift
if let value = myMap["key2"] {
  print(value) // prints "value2"
} else {
  print("Key does not exist")
}
106 chars
6 lines

Alternatively, you can use optional binding to retrieve the value, like this:

main.swift
if let value = myMap["key2"] {
  print(value) // prints "value2"
} else {
  print("Key does not exist")
}
106 chars
6 lines

That's it! Now you know how to retrieve the value associated with a key in a map in Swift.

related categories

gistlibby LogSnag