In this tutorial you will learn about the Swift Dictionaries and its application with practical example.
Swift Dictionaries
In Swift Dictionary is an unordered collection of multiple key-value pairs of same type. Dictionary is similar to associative arrays or hashes consist of key-value pairs. In dictionary each of the value is associated with a unique key, and this key is used to accessed corresponding dictionary value. In Swift, dictionaries are strongly typed, which means it is mandatory to specify types for both the keys and the values.
- Swift Dictionaries
- Declaring Dictionaries
- Initializing Dictionary
- Swift Initializing an Empty Dictionary
- Accessing Dictionary Elements In Swift
- )
- Swift Get Dictionary Elements Count
- Swift Add Elements to Dictionary
- Swift Update Dictionary Element
- Removing Dictionary Elements in Swift
- Iterating Over a Dictionary in Swift
- Iterating Over a Dictionary Keys
- Iterating Over a Dictionary Values
All the keys in a dictionary have the same type and all the values also have the same type, it is not necessary that the keys and values both of the same type. The type of any dictionary can be determined by the type of the keys and the type of the values it holds. A dictionary of type[Int:String] has keys of type Int and values of type String.
Declaring Dictionaries
In Swift, a dictionary can be declared using square brackets as following –
Syntax 1:-
1 |
var DictionaryName : Dictionary<KeyType, ValueType> |
OR
Syntax 2:-
1 |
var DictionaryName : [KeyType : ValueType] |
Here, DictionaryName is replaced with the actual dictionary variable name and KeyType and ValueType are replaced with the data type of key and value respectively.
Initializing Dictionary
In Swift, we can initialize a dictionary with a dictionary literal as following –
Syntax:-
1 |
var DictionaryName : [KeyType : ValueType] = [key:value, key:value, ...] |
Here, a dictionary literal is a list of key-value pairs, separated by commas, surrounded by a pair of square brackets. A key-value pair is a combination of a key and a value separate by a colon(:).
Example:-
1 2 3 4 5 |
var nums: [String:Int] = [ "one" : 1, "two" : 2, "three" : 3 ] |
Swift Initializing an Empty Dictionary
There are multiple ways we can initialize an empty dictionary –
Syntax 1:- Full Syntax
1 |
let empty1 : Dictionary<String, Int> = Dictionary<String, Int>() |
Syntax 2:- Shorthand Method
1 |
let empty2 : [String : Int] = [String : Int]() |
Syntax 3:- Empty Dictionary Using Dictionary Literals
1 |
var empty3 : [String: Int] = [:] |
Note:- If we don’t specify the type explicitly then Swift automatically infers the type.
Accessing Dictionary Elements In Swift
In swift a dictionary element can simply be accessed using subscript syntax, in order to access any specific dictionary element we need to pass associated key within the brackets.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var nums: [String:Int] = [ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 ] print("W3Adda - Accessing Dictionary Elements") print(nums["one"]) print(nums["two"]) print(nums["three"]) print(nums["four"]) print(nums["five"]) |
Output:-
Here, dictionary value returned by subscript can be unwrapped using optional binding or forced value operator (!) as following –
Example:-
1 2 3 4 5 6 7 |
// Unwaraping the optional using optional binding if let num = nums["four"] { print(num) // 4 } // Unwaraping the optional using the forced value operator (!) print(nums["four"]!) // 4 |
Swift Checking If a Dictionary Is Empty (isEmpty)
In Swift, isEmpty property can be used to check whether the given dictionary is empty or not.The isEmpty property returns a boolean value to indicate whether the dictionary is empty or not.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var nums: [String:Int] = [ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 ] print("W3Adda - Check empty dictionary using isEmpty property.") if nums.isEmpty{ print("Dictionary is empty.") } else{ print("Dictionary is not empty.") } |
Output:-
Swift Get Dictionary Elements Count
In swift count property can be used to get the count of elements of given dictionary.
Example:-
1 2 3 4 5 6 7 8 9 |
var nums: [String:Int] = [ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 ] print("W3Adda - Get dictionary element count.") print(nums.count) |
Output:-
Swift Add Elements to Dictionary
In swift, we can add a new item to dictionary by simply taking a new key of appropriate type and assign new value of appropriate type to it.
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
var nums: [String:Int] = [ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 ] nums["six"] = 6 print("W3Adda - Swift insert an Item into dictionary.") print(nums) |
Output:-
Swift Update Dictionary Element
The simplest way update a dictionary element values by assigning new values to associated key.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
var students: [String:Int] = [ "John" : 10, "Doe" : 20, "Alex" : 30 ] print("W3Adda - Swift update an Item into dictionary.") print("Before update") print("Alex\'s marks :\(students["Doe"]!)") students["Doe"] = 50 print("After update") print("Alex\'s marks :\(students["Doe"]!)") |
Output:-
Dictionary element can also be updated using updateValue(_, forKey: _) method as following –
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
var students: [String:Int] = [ "John" : 10, "Doe" : 20, "Alex" : 30 ] print("W3Adda - Swift update an Item into dictionary.") print("Before update") print("John\'s marks :\(students["John"]!)") students.updateValue(75, forKey: "John") print("After update") print("John\'s marks :\(students["John"]!)") |
Output:-
Removing Dictionary Elements in Swift
The simplest way remove a dictionary element values by assigning nil to associated key, alternatively we can remove an element using removeValue(forKey: _) method.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
print("W3Adda - Swift remove an element from dictionary.") print("Before Delete") print(students) // Remove dictionary element by assigning nil students["Doe"] = nil // Remove dictionary element using removeValue method students.removeValue(forKey: "John") print("After Delete") print(students) |
Output:-
Iterating Over a Dictionary in Swift
In Swift, we can loop through the dictionary elements using for-in loop as following –
Example:-
1 2 3 4 5 |
var students: [String:Int] = ["John" : 10, "Doe" : 20, "Alex" : 30] print("W3Adda - Iterating Dictionary Elements.") for (key, value) in students { print("\(key) - \(value)") } |
Output:-
Iterating Over a Dictionary Keys
In Swift, we can loop through the dictionary keys only using keys property as following –
Example:-
1 2 3 4 5 |
var students: [String:Int] = ["John" : 10, "Doe" : 20, "Alex" : 30] print("W3Adda - Iterating Dictionary Keys.") for key in students.keys { print("\(key)") } |
Output:-
Iterating Over a Dictionary Values
In Swift, we can loop through the dictionary values only using values property as following –
Example:-
1 2 3 4 5 |
var students: [String:Int] = ["John" : 10, "Doe" : 20, "Alex" : 30] print("W3Adda - Iterating Dictionary Values.") for val in students.values { print("\(val)") } |
Output:-