Contents

Swift Dictionary

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. Swift is actively developed by the open-source community. It offers a collection called dictionaries, which consists of key-value pairs.

A dictionary is an unordered collection where a key maps to a value. A key can be of any type, such as a string or integer, while the value associated with that key can also be any type of data.

Creating a Dictionary

In Swift, a dictionary is created by associating key-value pairs. The key should always be a single item, while the value can be a single item or even a collection such as an array or another dictionary.

Syntax:

				
					var someDictionary = [keyType: valueType](key: value)

				
			

Here, keyType and valueType define the types of keys and values, and they are separated by a colon.

Example:

				
					// Swift program to create a dictionary
var someDictionary: [String: String] = ["fruit": "Apple", "vegetable": "Carrot"] 

// Displaying key-value pair
print(someDictionary)

				
			

Output:

				
					["vegetable": "Carrot", "fruit": "Apple"]

				
			

Creating an Empty Dictionary

An empty dictionary contains no key-value pairs. It can be used for storing data as key-value pairs.

Syntax:

				
					var emptyDictionary = [keyType: valueType][:]

				
			

Example:

				
					// Creating an empty dictionary
var emptyDictionary = [String: String][:]
print(emptyDictionary) // Output: [:]

				
			

Changing the Value in a Dictionary

In Swift, the values of a dictionary can be updated using square brackets []. If the key is not found, a new key-value pair is added.

Syntax:

				
					Dictionary_name[key] = value

				
			

Example:

				
					// Swift program to change the value of dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit", "three": "Tony"]

// Displaying original dictionary
print("Original dictionary: ", someDictionary)

// Changing the value
someDictionary["two"] = "Priya"

// Displaying updated dictionary
print("Updated dictionary: ", someDictionary)

				
			

Output:

				
					Original dictionary:  ["two": "Rohit", "one": "Mohit", "three": "Tony"]
Updated dictionary:  ["two": "Priya", "one": "Mohit", "three": "Tony"]

				
			

Accessing Elements of a Dictionary

You can access the keys and values separately from the dictionary.

1. Accessing Keys: To access the keys of a dictionary, use the keys property, which returns all the keys from the dictionary.

Syntax:

				
					Dictionary_name.keys

				
			

Example:

				
					// Accessing all the keys from the dictionary
var result = Array(someDictionary.keys)

// Displaying keys
print("Keys:", result)

				
			

Output:

				
					Keys: ["two", "three", "one"]

				
			

2. Accessing Values: To access the values of a dictionary, use the values property, which returns all the values from the dictionary.

Syntax:

				
					Dictionary_name.values
				
			

Example:

				
					// Accessing all the values from the dictionary
var result = Array(someDictionary.values)

// Displaying values
print("Values:", result)

				
			

Output:

				
					Values: ["Priya", "Mohit", "Tony"]

				
			

Iterating Over a Dictionary

You can iterate over a dictionary using a for-in loop. The key-value pairs’ order is not guaranteed, as dictionaries are unordered collections.

Syntax:

				
					for (key, value) in someDictionary {}

				
			

Example:

				
					// Iterating over a dictionary
for (key, value) in someDictionary {
    print("\(key): \(value)")
}

				
			

Output:

				
					two: Priya
three: Tony
one: Mohit

				
			

Creating a Dictionary from Two Arrays

You can create a dictionary from two arrays of the same size, where the first array represents the keys and the second array represents the values.

Syntax:

				
					var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))

				
			

Example:

				
					// Creating arrays
var someArray = ["one", "two", "three"]
var someArray2 = ["Mohit", "Rohit", "Tony"]

// Creating a dictionary from arrays
var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))

// Displaying the dictionary
print(someDictionary)

				
			

Output:

				
					["one": "Mohit", "two": "Rohit", "three": "Tony"]

				
			

Removing Items from a Dictionary

To remove a key-value pair from a dictionary, use the removeValue(forKey:) method. This method returns the value associated with the removed key or nil if the key is not found.

Syntax:

				
					let areEqual = mySet1 == mySet2

				
			

Example:

				
					// Removing key-value pair from dictionary
someDictionary.removeValue(forKey: "one")

// Displaying updated dictionary
print(someDictionary)

				
			

Output:

				
					["two": "Rohit", "three": "Tony"]

				
			

Converting a Dictionary to an Array

You can convert a dictionary into an array of key-value pairs. This results in two arrays: one for keys and another for values.

Syntax:

				
					Array(dictionary)

				
			

Example:

				
					// Converting dictionary to arrays
var dictArray1 = Array(someDictionary.keys)
var dictArray2 = Array(someDictionary.values)

// Displaying arrays
print(dictArray1)
print(dictArray2)

				
			

Output:

				
					["two", "three", "one"]
["Rohit", "Tony", "Mohit"]

				
			

Dictionary Properties

count Property: The count property returns the number of key-value pairs in the dictionary.

Syntax:

				
					dictionary.count

				
			

Example:

				
					var planets = ["Mercury": "Closest to the sun", "Venus": "Second closest", "Earth": "Third closest"]
print("Total planets: \(planets.count)")

				
			

Output:

				
					Total planets: 3

				
			

isEmpty Property: The isEmpty property checks if a dictionary is empty or contains key-value pairs.

Syntax:

				
					dictionary.isEmpty

				
			

Example:

				
					var emptyDictionary = [String: String]()

print("Is the dictionary empty? \(emptyDictionary.isEmpty)")  // true
print("Is the planets dictionary empty? \(planets.isEmpty)")  // false

				
			

Output:

				
					Is the dictionary empty? true
Is the planets dictionary empty? false