Swift is a programming language designed to work with Apple’s Cocoa and Cocoa Touch frameworks. It is intended to be a modern, safe, and flexible alternative to Objective-C. It is built with the open-source community in mind, and it is actively developed by members of the Swift community. Swift is a modern, safe, and flexible alternative to Objective-C.
Swift has something called dictionaries, which is a collection of key-value pairs. These collections of key-value pairs are called dictionaries. It is an unordered collection of key-value pairs. In the dictionary, a unique identifier is known as a key, and a key stores a value. When a dictionary is assigned to a variable then that means the dictionary is mutable(you can modify) but when the dictionary is assigned to a constant then it is immutable(you cannot modify). In a dictionary, a key can be of any type with string, integer, etc. In this article, we will learn about the dictionary collection type in Swift.
Creating a dictionary
In swift, a dictionary is a collection of key-value pairs. We can use any type of data as a key and any type of data as a value. We can create a dictionary using the (key:value) syntax. A key should always be a single item. But a value can be a single item or a collection of items, like an array or a dictionary. To create a dictionary, we use the following syntax:
Syntax:
var someDictionary = [keyType: valueType](key : value)
Here, keyType and valueType are the types of keys and values in the dictionary and they are separated by a colon.
Example:
Swift
var someDictionary: [ String : String ] = [ "fruit" : "Apple" , "vegetable" : "Carrot" ]
print (someDictionary)
|
Output:
["vegetable": "Carrot", "fruit": "Apple"]
Creating an empty dictionary
An empty dictionary is a dictionary with no key-value pairs in it. An empty dictionary doesn’t have any initial values. It can be used for storing data in key-value pairs. It acts as a container for storing data. To create an empty dictionary, you use the following syntax:
Syntax:
var emptyDictionary = [keyType: valueType][:]
Here, keyType and valueType are the types of keys and values in the dictionary. And the ([:]) is an empty dictionary literal used to create an empty dictionary.
Change the value of Dictionary
In Swift, we are allowed to change the values of the dictionary using []. The bracket [] changes the value associated with the given key in the dictionary. Similarly, you can also add new key-value pair in the dictionary. If the given key is not present then that key and value pair are added to the dictionary.
Syntax:
Dictionary_name[key] = value
Example:
Swift
var someDictionary = [ "one" : "Mohit" , "two" : "Rohit" ,
"three" : "Tony" ]
print ( "Original dictionary: " , someDictionary)
someDictionary[ "two" ] = "Priya"
print ( "Updated dictionary: " , someDictionary)
|
Output:
Original dictionary: ["two": "Rohit", "one": "Mohit", "three": "Tony"]
Updated dictionary: ["two": "Priya", "one": "Mohit", "three": "Tony"]
Accessing the elements of Dictionary
In the dictionary, we can easily access the key and values separately.
1. Accessing keys
To access the keys of a dictionary we use the keys property. This property returns all the keys from the dictionary.
Syntax:
Dictionary_name.keys
Example:
Swift
var someDictionary = [ "one" : "Mohit" , "two" : "Rohit" ,
"three" : "Tony" ]
var result = Array (someDictionary.keys)
print ( "Keys:" , result)
|
Output:
Keys: ["two", "three", "one"]
2. Accessing values
To access the values of a dictionary we use the values property. This property returns all the values from the dictionary.
Syntax:
Dictionary_name.values
Example:
Swift
var someDictionary = [ "one" : "Mohit" , "two" : "Rohit" ,
"three" : "Tony" ]
var result = Array (someDictionary.values)
print ( "Values:" , result)
|
Output:
Values: ["Tony", "Mohit", "Rohit"]
Iterating Over a Dictionary
Sometimes we need to iterate over a dictionary, and it is not feasible to manually use subscript to access the value of a key for each key-value pair in the dictionary. So we can use a for-in loop to iterate over the dictionary. Remember the order of the key-value pairs in the dictionary is not guaranteed to be the same as the order in which they were inserted.
Syntax:
for (key, value) in someDictionary {}
Example:
Swift
var someDictionary = [ "one" : "Mohit" , "two" : "Rohit" ,
"three" : "Tony" ]
for (key, value) in someDictionary
{
print ( "\(key): \(value)" )
}
|
Output:
three: Tony
one: Mohit
two: Rohit
Creating a Dictionary from an Array
If we have two arrays of the same size, and we want to merge them, to form a dictionary with key as the first array and value as the second array then you are allowed to do this in Swift. The size of both arrays should be the same.
Syntax:
var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))
Here, array1 is the key and array2 is the value. So, the above syntax will create a dictionary with key as array1 and value as array2
Example:
Swift
var someArray = [ "one" , "two" , "three" ]
var someArray2 = [ "Mohit" , "Rohit" , "Tony" ]
var someDictionary = Dictionary (uniqueKeysWithValues: zip(
someArray, someArray2))
print (someDictionary)
|
Output:
["one": "Mohit", "two": "Rohit", "three": "Tony"]
Removing items from a Dictionary
As we have seen, a method to get and set the value of a key in a dictionary. But sometimes we want to remove a key-value pair from a dictionary. So, to remove a key-value pair from a dictionary, we use the removeValue(forKey:) method. This method returns the value for the key that was removed, or nil if the key was not present in the dictionary.
Syntax:
dictionary.removeValue(forKey: key)
Example:
Swift
var someDictionary = [ "key1" : "value1" , "key2" : "value2" ]
someDictionary.removeValue(forKey: "key1" )
print (someDictionary)
|
Output:
["key2": "value2"]
Convert a dictionary to an array
Swift allows us to convert a dictionary to an array of key-value pairs. Here, two arrays will be created one for storing keys and one for storing values.
Syntax:
Array(dictionary)
Where dictionary is the dictionary we want to convert to an array.
Example:
Swift
var dict = [ "Arpit" :100, "Robin" :90, "Nami" :90]
var dictArray1 = Array (dict.keys)
var dictArray2 = Array (dict.values)
print (dictArray1)
print (dictArray2)
|
Output:
["Arpit", "Robin", "Nami"]
[100, 90, 90]
Dictionary Properties
Swift offers a number of properties and methods to help you work with the dictionary. The count and the empty property are the most important properties of a dictionary. The count property returns the number of key-value pairs in the dictionary. The empty property returns true if the dictionary has no key-value pairs, and false if it has at least one key-value pair.
count Property
Count property returns the count of the key-value pairs present in the given dictionary. This property is useful when you want to iterate over the dictionary. It returns an integer value, the number of key-value pairs in the dictionary.
Syntax:
dictionary.count()
Here, the dictionary is the name of the dictionary and count is the name of the property.
Example:
Swift
var planets = [ "Mercury" : "The closest planet to the sun" ,
"Venus" : "The second closest planet to the sun" ,
"Earth" : "The third closest planet to the sun" ,
"Mars" : "The fourth closest planet to the sun" ,
"Jupiter" : "The fifth closest planet to the sun" ,
"Saturn" : "The sixth closest planet to the sun" ,
"Uranus" : "The seventh closest planet to the sun" ,
"Neptune" : "The eighth closest planet to the sun" ]
print ( " Total number of planets in our solar system are \(planets.count)" )
|
Output:
Total number of planets in our solar system are 8
isEmpty Property
Suppose we have a dictionary and we want to perform some operation on it. If the dictionary is empty, we can’t perform any operation on it. So, we can use the empty property to check if a dictionary is empty or not. The empty property returns true if the dictionary has no key-value pairs, and false if it has at least one key-value pair.
Syntax:
dictionary.isEmpty()
Here, the dictionary is the name of the dictionary and isEmpty is the name of the property.
Example:
Swift
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
var emptyDictionary = [ String : String ]()
var fruits = [ "Apple" : "Red" , "Orange" : "Orange" ,
"Banana" : "Yellow" ]
print ( "is numbers dictionary empty? \(numbers.isEmpty)" )
print ( "is emptyDictionary dictionary empty? \(emptyDictionary.isEmpty)" )
print ( "is fruits dictionary empty? \(fruits.isEmpty)" )
|
Output:
is numbers dictionary empty? false
is emptyDictionary dictionary empty? true
is fruits dictionary empty? false
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...