find data in dictionairy in swift

To find data in a dictionary in Swift, you can use the subscript syntax or the contains method of the dictionary. Here are two ways to do it:

  1. Using subscript syntax:
main.swift
let myDictionary = ["name": "John", "age": 25, "city": "New York"]

if let age = myDictionary["age"] as? Int {
    print("Age: \(age)")
} else {
    print("Age not found")
}
174 chars
8 lines
  1. Using the contains method:
main.swift
let myDictionary = ["name": "John", "age": 25, "city": "New York"]

if myDictionary.contains(where: { $0.key == "age" }) {
    let age = myDictionary["age"] as? Int
    print("Age: \(age)")
} else {
    print("Age not found")
}
228 chars
9 lines

In the above examples, we are searching for the value associated with the key "age" in the dictionary. If the key is found, we can access the value using subscript syntax or the contains method.

Make sure to handle the optional value appropriately, as shown in the examples, to avoid runtime errors when accessing the value.

Remember to replace "age" with the key you are searching for in your dictionary.

related categories

gistlibby LogSnag