Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
In Swift, a dictionary is a collection that stores associations between keys of the same type and values of the same type in an unordered list. The key-value pairs in a dictionary are unique, meaning there can't be duplicate keys.
To create an empty dictionary, you can use the initializer syntax:
var dictionaryName: [KeyType: ValueType] = [:]
var namesOfIntegers: [Int: String] = [:]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London Heathrow"
airports["LHR"] = "London Heathrow International"
let airportName = airports["LHR"]
airports["DUB"] = nil
let numberOfAirports = airports.count
if airports.isEmpty { print("The airports dictionary is empty.") } else { print("The airports dictionary is not empty.") }
for (airportCode, airportName) in airports { print("\(airportCode): \(airportName)") }
Dictionaries in Swift are powerful and efficient, allowing for fast access to values using a key. They're particularly useful when you need to group related items without ordering them. However, it's essential to remember that since dictionaries are unordered, the sequence of their elements is arbitrary.
How to create dictionaries in Swift:
Description: Dictionaries in Swift store key-value pairs and are created using square brackets with the format key: value
.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2]
Accessing and modifying dictionary elements in Swift:
Description: You can access and modify dictionary elements using subscript syntax.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] // Accessing let appleCount = fruits["Apple"] // 3 // Modifying fruits["Banana"] = 8
Adding and removing items in a Swift dictionary:
Description: Items can be added using subscript notation and removed using the removeValue(forKey:)
method.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] // Adding fruits["Grapes"] = 4 // Removing fruits.removeValue(forKey: "Banana")
Iterating over dictionary key-value pairs in Swift:
Description: You can iterate over a dictionary using a for-in loop to access key-value pairs.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] for (fruit, count) in fruits { print("\(fruit): \(count)") }
Dictionary filtering and mapping in Swift:
Description: Swift provides methods like filter
and map
for filtering and transforming dictionary elements.
Code:
var prices: [String: Double] = ["Apple": 1.0, "Banana": 0.5, "Orange": 1.2] let expensiveFruits = prices.filter { $0.value > 1.0 } let doubledPrices = prices.mapValues { $0 * 2 }
Swift dictionary methods and functions:
Description: Swift dictionaries provide various methods and functions for common operations, such as count
, isEmpty
, and keys
.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] let numberOfFruits = fruits.count let isEmpty = fruits.isEmpty let fruitNames = Array(fruits.keys)
Using optionals in Swift dictionaries:
Description: Dictionary lookups return optionals to handle cases where a key may not exist.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] if let appleCount = fruits["Apple"] { print("Number of Apples: \(appleCount)") }
Swift dictionary merging and updating:
Description: Dictionaries can be merged using the merge
method, and values can be updated using the updateValue
method.
Code:
var fruits: [String: Int] = ["Apple": 3, "Banana": 5, "Orange": 2] let additionalFruits: [String: Int] = ["Grapes": 4, "Cherry": 6] // Merging fruits.merge(additionalFruits) { (current, new) in new } // Updating fruits.updateValue(7, forKey: "Banana")