Monday, June 10, 2019

Dictionaries in Swift, iOS

It is an unordered collection that stores associations between keys and values of same type with no defining ordering. Each value is associated with unique key that acts as an identifier for the value in dictionary. A key is used to store and retrieve values from dictionary. There are two ways of a dictionary declaration. 

If keys and values are consistent types, we do not need to declare the type of dictionary in the declaration.

Adding / Modifying / Removing to a dictionary
For addition subscript notation or updateValue(_:forKey) method can be used.

For removing a pair from a dictionary subscript notation and removeValue(forKey:) method can be used. This method returns the value that was removed.

For retrieving pairs from a dictionary subscript notation can be used. It is possible to use optional binding, forced unwrapping or determine if the value exists to retrieve the pair. If you are absolutely sure that the key exists then only in this case forced unwrapping can be used.

It is possible to iterate through a dictionary and return key pair, which can be decomposed into named constants.


It is possible to retrieve only the keys or values independently.

As mentioned before dictionaries are unordered collections so when you iterate through them there is no guarantee that it will be listed in an order. But there might be occasions that you want iteration in an ordered manner and for those cases sort(_:) method can be used. This will return an array contained sorted elements of a dictionary. In below code $0.0 is first key value pair and $0.1 is second key value pair. These pairs are compared and will be ordered based on this comparison.Then map method is used to retrieve data for key or value.



No comments:

Post a Comment