Swift Dictionary
What is Swift Dictionary?
@frozen struct Dictionary<Key, Value> where Key : Hashable
Create a dictionary.
var userIdNamesDictionary:Dictionary<String,String> = [:]
var userIdNamesDictionary2:[String:String] = [:]
Style 3:
Inferring based on the values in the dictionary during initialization. The entry before the colon is key and after the colon is value corresponding to the key, we can add multiple key and value pairs by separating it with comma.
var userIdNamesDictionary3 = ["1":"Adam","2":"Rose"]
Read value from dictionary.
userIdNamesDictionary3["1"]
If there is no value for the provided key value is nil.
Update items in dictionary.
userIdNamesDictionary3.updateValue("Eden", forKey: "1")
Bring it to actual use, as listed below.
if let oldName = userIdNamesDictionary3.updateValue("Eden", forKey: "1") {
print("For Key 1, oldValue \(oldName) is updated to Eden")
} else {
print("For Key 1, value does not exists hence adding a new value for key 1")
}
Style 2:
Simple and easy one with subscript operator. If the value is found it updates else inserts. But here we don't get the old value in case it's being replaced.
userIdNamesDictionary3["1"] = "John"
Delete items from dictionary.
userIdNamesDictionary3.removeValue(forKey: "2")
Simply removes the value for a given key, but if need to know the value as well. May to show a message in the Alert with the name, for which the id is being removed.
if let valueBeingRemoved = userIdNamesDictionary3.removeValue(forKey: "2") {
print("User being removed is \(valueBeingRemoved)")
} else {
print("Cannot finding a matching user to be removed from dictionary")
}
Style 2:
Simpler approach if we are not interested in getting the value.
userIdNamesDictionary3["1"] = nil
If there are any suggestion or any questions feel free to comment here.
Comments
Post a Comment