Swift Dictionaries

In swift, dictionaries are used to store values with key-value pair association in an unordered manner. In dictionaries, we can store the same type of keys and the same type of values with no defined order. The keys in dictionaries must be unique and those will act as identifiers for the values in dictionaries.

 

We can use dictionaries in swift programming language whenever we want to get values based on key values.

 

Following is the pictorial representation of dictionaries in a swift programming language.

 

Swift Dictionary Collection Types with Examples

 

If you observe the above image we are storing values with key-value pair association in an unordered manner in swift dictionary collection type.

 

In swift, we can create dictionaries by using dictionary literal.  The dictionary literal contains a list of comma-separated key-value pairs, in which a colon separates each key from its associated value surrounded by square brackets.

 

We can assign a dictionary literal to any variable or constant or any function in a swift programming language based on our requirements.

Syntax of Swift Dictionaries

Following is the syntax of defining dictionary collection types in a swift programming language.

 

Dictionary<Key, Value>()

 

Or

 

 [Key: Value]()

In the above syntax, the Key is the type of value that can be used as a dictionary key and Value is the type of value that dictionary stores for the defined keys.

Creating a Dictionaries in Swift

The following are the different ways of creating empty dictionaries with key-value pair types in the declaration.

 

// using Dictionary

let nums = Dictionary<Int, String>()

print(nums.count)

// It prints 0

 

// without dictionary

let nums = [Int: String]()

print(nums.count)

// It prints 0

The above examples will create an empty dictionary of [Int, String] to store Int type of keys and String type of values.

 

The following are the different ways of defining or declaring dictionaries with keys and values in a swift programming language.

 

// with Dictionary Literal

var names = Dictionary<String, Int>()

names = ["Suresh": 1, "Rohini": 2]

print(names)

// It prints [Suresh: 1, Rohini: 2]

 

// without Dictionary Literal

var names = [Int: String]()

names = [1: "Suresh", 2: "Rohini"]

print(names)

// It prints [1: Suresh, 2: Rohini]

Now we will see how to access dictionary elements in a swift programming language with examples.

Accessing Dictionary Elements in Swift

In swift, we can access dictionary elements by using key values based on our requirements.

 

Following is the example of accessing elements in Dictionary using key values.

 

// with Key-Value Data Types

var names = [Int: String]()

names = [1: "Suresh", 2: "Rohini"]

print(names)

print(Array(names.keys))

print(Array(names.values))

print(names[1])

print(names[2])

If you observe above example we defined dictionary object “names”, Key-Value pair data type and accessing dictionary values in different ways.

 

When we run the above program in a swift playground that will return a result like as shown below

 

[1: Suresh, 2: Rohini]

[1, 2]

[Suresh, Rohini]

Suresh

Rohini

Following is another example of accessing dictionary elements using Key values.

 

// with Key-Value Data Types

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

print(names["x"])

print(names["y"])

print(names["z"])

If you observe above example we defined dictionary object “names” and using Key-Value pair without defining data type and accessing dictionary values using Key values.

 

When we run the above program in the swift playground that will return a result like as shown below

 

Suresh

Rohini

Praveen

This is how we can access the elements in dictionary objects in a swift programming language based on our requirements.

Check Dictionary Empty or Not in Swift

By using isEmpty property we can check whether the given dictionary contains elements or not in a swift programming language.

 

Following is the example of using isEmpty property to check whether the given dictionary contains elements or not.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

if names.isEmpty  {

print("Dictionary is Empty")

} else {

print("Dictionary Contains Elements")

}

If you observe above example we are checking whether dictionary contains elements or not using isEmpty property.

 

When we run the above program in a swift playground that will return a result like as shown below

 

Dictionary Contains Elements

This is how we can check whether the given dictionary contains elements or not in a swift programming language based on our requirements.

Get Dictionary Elements Count in Swift

In swift, by using count property we can get the count or number of elements that exist in the dictionary.

 

Following is the example of using count property to get the number of elements that exist in the dictionary.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

if names.count > 0 {

print("Dictionary Contains \(names.count) Elements")

} else {

print("No Elements")

}

If you observe above example we are checking Dictionary elements count using count property.

 

When we run the above program in the swift playground that will return a result like as shown below

 

Dictionary Contains 3 Elements

This is how we can get a number of elements that exist in the dictionary in a swift programming language based on our requirements.

Add Elements to Dictionary in Swift

In swift, we can insert or add new items to a dictionary object by using the new key of the appropriate type and assign a new value of appropriate type.

 

Following is the example of inserting new elements in dictionary object in the swift programming language.

 

var names = ["x": "Suresh", "y": "Rohini"]

names["z"] = "Praveen"

names["a"] = "Sateesh"

print(names)

If you observe above example we are adding new items to a dictionary object “names” by assigning new key values.

 

When we run the above program in a swift playground that will return a result like as shown below

 

[x: Suresh, y: Rohini, z: Praveen, a: Sateesh]

This is how we can insert or add elements to an existing dictionary in a swift programming language based on our requirements.

Update or Modify Elements in Dictionary

In swift, we can modify or update dictionary object element values by assigning new values to appropriate keys.

 

Following is the example of updating elements in dictionary object in the swift programming language.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

names["z"] = "Sateesh"

print(names)

If you observe above example we are updating element in dictionary object “names” by assigning new value to key “z”.

 

When we run the above program in a swift playground that will return a result like as shown below.

 

[y: Rohini, x: Suresh, z: Sateesh]

We have another alternative way, updateValue(_, forKey: _) method in the swift programming language to set or update the values of a particular key in a dictionary object.

 

Following is the example of updating elements in dictionary object in a swift programming language.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

if let oldValue = names.updateValue("Sateesh", forKey: "z") {

print("Old Value of Key z is: \(oldValue)")

}

print(names)

If you observe above example we are updating element in dictionary object “names” by using updateValue() method and getting old value of key “z” before update.

 

When we run the above program in a swift playground that will return a result like as shown below.

 

Old Value of Key z is: Praveen

[y: Rohini, x: Suresh, z: Sateesh]

This is how we can update elements in dictionary objects based on our requirements in swift programming language.

Remove Dictionary Elements in Swift

In Swift, we can easily delete or remove the key-value pair in a dictionary by assigning a value of nil to the respective key and alternatively we can use removeValueForKey() method to remove key-value pair.

 

Following is the example of removing elements in the dictionary by assigning nil value to respective keys.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

names["z"] = nil

print(names)

If you observe above example we are deleting key-value pair in dictionary by assigning nil value.

 

When we run the above example we will get a result like as shown below.

 

[y: Rohini, x: Suresh]

Following is another way of removing elements in a dictionary by using the removeValueForKey() method.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

names.removeValueForKey("z")

print(names)

If you observe above example we are deleting key-value pair in dictionary by using removeValueForKey method.

 

When we run the above example we will get a result like as shown below

 

[y: Rohini, x: Suresh]

This is how we can delete key-value pairs in Dictionary objects based on our requirements in swift programming language.

Iterating Over a Dictionary in Swift

By using for-in loop we can iterate or loop through elements in dictionary objects and use it in our applications based on our requirements in swift programming language.

 

Following is the example of iterating over elements in the dictionary object by using the for-in loop.

 

var names = ["x": "Suresh", "y": "Rohini", "z": "Praveen"]

for (key, value) innames {

print("\(key) - \(value)")

}

When we run above example we will get result like as shown below

 

y - rohini

x - suresh

z - praveen

This is how we can loop through or iterate over Dictionary elements in a swift programming language based on our requirements.