Swift Dictionary

What is Swift Dictionary?

Swift Dictionary is a hash table providing fast access to the keys it contains.  Entries in the table are identified with the help of key, which is hash able and the entries accessed are objects.

In Swift Dictionary is structure with Key and Value, where Key is Hashable as can be understood from the Apple Document 

@frozen struct Dictionary<Key, Value> where Key : Hashable

Let's perform some CRUD operations on a dictionary.

Create a dictionary.

There are multiple ways to create a dictionary. 

Style 1:

var userIdNamesDictionary:Dictionary<String,String> = [:]



Style 2:

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.

To read value for a key use subscript operator

userIdNamesDictionary3["1"]


If there is no value for the provided key value is nil.


Update items in dictionary.

Two ways to update items in a dictionary.

Style 1:

Used when we need to know the older value which is being updated for a key. Older value is returned only if the key exists.
In case the key does not exists it performs an add operation and return nil.

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.

There are again two ways you can remove or delete values for a key.

Style 1: 

In case we want to get the value being removed we can use this approach, returned value is optional and so can be nil in case there is no match found for the key

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

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

Custom Editing Control for UITableViewCell , like iPhone Mail Appliation