alchemy-2024-SWIFT

Dictionary

[!NOTE] You need to use [key:value, ]

let Details: [String: String] = ["Name": "Girish", "age": "29"]
print(Details)
  1. Retrieve the values from dict
Details["Name"]

Details["FirstName"]  //null --> Since the key is not present
  1. Adding New key value pair to dict
Details["firstname"] = "Girish"
  1. Update value

    updateValue(value : forKey: <key>)

[!NOTE] This will return the previous value if not present it will return nil and then update the value

let previousLastName: String? = Details.updateValue("V", forKey: "lastname")
print("previous lastname \(previousLastName ?? "nil") and current value \(Details)")
  1. Removing items from dictionary

    removeValue(forkey:)

    another way is by setting the value to nil

Details.removeValue(forKey: "lastname")
Details["lastname"] = nil
  1. Methods in dict
Details.count
Details.keys
Array(Details.values)

image