Swift Dictionaries

  Total Views : 241
  Comments : 0
  Keywords : Swift dictionaries are used to store values with key-value pair in unordered list, Swift dictionary is an unordered collection of elements where each element consists of unique key & value

Here we will learn dictionaries in swift with examples and how to use swift dictionaries to store keys of same type and values of same type in unordered manner, create dictionaries in swift, add or remove elements in dictionaries, access dictionary elements with keys, count elements in dictionary, check whether dictionary is empty or not and iteration over a dictionary elements with examples.

Swift Dictionaries

In swift dictionaries are used to store values with key-value pair association in unordered manner. In dictionaries we can store same type of keys and 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 value.

 

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

 

Swift Dictionary Collection Types with Examples

 

If you observe above image we are storing values with key-value pair association in 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 dictionary literal to any variable or constant or any function in swift programming language based on our requirements.

Syntax of Swift Dictionaries

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

 

Dictionary<Key, Value>()

 

Or

 

 [Key: Value]()

In 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

Following are the different ways of creating an empty dictionaries with key-value pair type in 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.

 

Following are the different ways of defining or declaring dictionaries with keys and values in 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 elemetns in 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 above program in swift playground that will return 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 above program in swift playground that will return result like as shown below

 

Suresh

Rohini

Praveen

This is how we can access the elements in dictionary objects in 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 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 above program in swift playground that will return result like as shown below

 

Dictionary Contains Elements

This is how we can check whether the given dictionary contains elements or not in 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 exists in dictionary.

 

Following is the example of using count property to get number of elements exists in 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 above program in swift playground that will return result like as shown below

 

Dictionary Contains 3 Elements

This is how we can get number of elements exists in dictionary in swift programming language based on our requirements.

Add Elements to Dictionary in Swift

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

 

Following is the example of inserting new elements in dictionary object in 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 above program in swift playground that will return 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 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 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 above program in swift playground that will return result like as shown below.

 

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

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

 

Following is the example of updating elements in dictionary object in 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 above program in swift playground that will return 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 object 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 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 dictionary by assigning nil value to respective key.

 

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 above example we will get result like as shown below.

 

[y: Rohini, x: Suresh]

Following is another way of removing elements in dictionary by using 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 above example we will get result like as shown below

 

[y: Rohini, x: Suresh]

This is how we can delete key-value pairs in Dictionary object 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 an 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 an elements in dictionary object by using 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 swift programming language based on our requirements.

 

NEXT

Swift Functions  
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User