Swift Dictionaries with Examples
Expert-led Online Courses: Elevate Your Skills, Get ready for Future - Enroll Now!
Dictionaries are one of the collection data types in Swift. They are unordered collections. It has key-value pairs in it. Each key is unique in a dictionary, but a key can have multiple values. It helps in efficient look-up. It maps two elements: key and value. The key and value can be of any data type.
This article will discuss how to create, modify and access dictionaries in Swift. We’ll also cover other concepts related to it, along with relevant examples.
Create Dictionary in Swift
We can create a dictionary by writing a var/let followed by the dictionary’s name. We can also write the type of key and value in the type declaration.
Syntax for creating a dictionary.
var exampleDictionary: [keyType: valueType] = [key1: value1, key2: value2, ..., keyN: valueN]
For example,
var dictionaryExample: [Int: String] = [ 2014: "DataFlair", 2023: "Swift"] print(dictionaryExample)
Output:
[2023: “Swift”, 2014: “DataFlair”]
Create an empty dictionary in Swift
We can create an empty dictionary in Swift. We do it by defining the data types of key and value.
Syntax for creating an empty dictionary.
var dictionaryExample = [keyType: valueType]()
Example given,
var dictionaryExample = [Int: String]()
Modify Dictionary in Swift
We can modify the elements of a dictionary. We can add elements or remove elements from it. We can also edit the values of the elements.
Add elements
We add new elements to the dictionary by assigning values. We assign new values to a new key of the dictionary. This key is written within [] brackets while assigning the value.
Syntax for adding a new element
var dictionaryExample[newKey] = newValue
For example,
var dictionaryExample = [ 2014: "DataFlair", 2023: "Swift"]
print("Original: \(dictionaryExample)")
dictionaryExample[2020] = "Dictionary"
print("Updated: \(dictionaryExample)")Output:
Original: [2023: “Swift”, 2014: “DataFlair”]
Updated: [2023: “Swift”, 2020: “Dictionary”, 2014: “DataFlair”]
Remove elements
We can also remove key-value pairs from the dictionary.
Syntax for removing elements from dictionaries.
someDictionary.removeValue(forKey: keyValue)
Example given,
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
print("Original: \(dictionaryExample)")
dictionaryExample.removeValue(forKey: 2020)
print("Updated: \(dictionaryExample)")Output:
Original: [2020: “Dictionary”, 2014: “DataFlair”, 2023: “Swift”]
Updated: [2014: “DataFlair”, 2023: “Swift”]
Change elements
We can change the values of elements in the dictionary by reassigning values to the particular key of the dictionary.
Syntax for changing the value.
dictionaryExample[key] = newValue
For example,
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
print("Original: \(dictionaryExample)")
dictionaryExample[2020] = "Collections"
print("Updated: \(dictionaryExample)")Output:
Original: [2014: “DataFlair”, 2020: “Dictionary”, 2023: “Swift”]
Updated: [2014: “DataFlair”, 2020: “Collections”, 2023: “Swift”]
Access elements of Dictionary
We can access the elements of a dictionary in Swift. We can do it either by using the key or the value property of the dictionary.
Access keys
To access keys, we use the keys property of a dictionary. For example,
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
print("Keys of the dictionary: \(dictionaryExample.keys)")Output:
Keys of the dictionary: [2020, 2023, 2014]
Access values
To access values, we use the values property of a dictionary.
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
print("Values of the dictionary: \(dictionaryExample.values)")Output:
Values of the dictionary: [“Dictionary”, “DataFlair”, “Swift”]
Swift Dictionary Properties and Methods
Swift provides a number of methods and properties to manipulate elements and use them at our convenience.
| Property/Method | Description |
| count | Gives the number of elements in a dictionary |
| isEmpty | Returns true if the dictionary is empty |
| shuffled() | Shuffles the order of elements in the dictionary |
| sorted() | Sorts the element in the dictionary |
| contains() | Check if the particular element is present in the dictionary or not |
| randomElement() | Gives random elements of the dictionary |
| firstIndex() | Gives index of the given element |
Filter in Dictionary
Swift offers a unique property which can filter values in a dictionary. For example,
var subjectMarks = ["Maths": 100, "Physics": 98, "Chemistry": 99, "English": 95, "French": 90]
var subjectWithAGrade = subjectMarks.filter{$0.value > 95}
print(subjectWithAGrade)Output:
[“Maths”: 100, “Chemistry”: 99, “Physics”: 98]
Swift Grouping Dictionary
We can group dictionary values based on several conditions we provide. The below example groups the subjects based on their first letter.
var subjectMarks = ["Maths": 100, "Physics": 98, "Chemistry": 99, "English": 95, "Music": 90, "Psychology": 94, "Economics": 92]
var groupedSubjects = Dictionary(grouping: subjectMarks.keys) {$0.first!}
print(groupedSubjects)Output:
[“P”: [“Physics”, “Psychology”], “M”: [“Maths”, “Music”], “C”: [“Chemistry”], “E”: [“Economics”, “English”]]
Swift Loop and dictionary
We can iterate through the elements of the dictionary using a for-in loop. Example given,
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
for (key, value) in dictionaryExample{
print("Key: \(key), Value: \(value)")
}Output:
Key: 2023, Value: Swift
Key: 2014, Value: DataFlair
Key: 2020, Value: Dictionary
Arrays and Dictionaries in Swift
Swift provides methods to convert arrays into dictionaries and a dictionary into arrays.
Arrays to dictionary
To convert arrays into a dictionary, we need two arrays. One array will correspond to the keys in the dictionary and the second array will correspond to the values.
Syntax to convert an array into a dictionary.
var newDictionary = Dictionary(uniqueKeysWithValues: zip(Array1, Array2)
For example,
var keysArray = [2023, 2020, 2014] var valuesArray = ["Swift", "Dictionary", "DataFlair"] var dictionaryExample = Dictionary(uniqueKeysWithValues: zip(keysArray, valuesArray)) print(dictionaryExample)
Output:
[2020: “Dictionary”, 2014: “DataFlair”, 2023: “Swift”]
Dictionary to arrays
We can convert a dictionary into 2 arrays. One array is made from the keys of the dictionary. Another array is made from the values of the array. For example,
var dictionaryExample = [2023: "Swift", 2020: "Dictionary", 2014: "DataFlair"]
var keysArray = dictionaryExample.keys
var valuesArray = dictionaryExample.values
print("Keys array: \(keysArray)")
print("Values array: \(valuesArray)")Output:
Keys array: [2023, 2020, 2014]
Values array: [“Swift”, “Dictionary”, “DataFlair”]
Conclusion
Swift dictionaries are a unique way to map data into keys and their values. It helps in handling data efficiently. In this article, we’ve seen how to create and modify arrays. We‘ve gone through how we can access them and use them with loops. We have also covered how we can convert arrays into dictionaries and vice-versa.
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

