Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - Dictionary

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.

Declaration:

To create an empty dictionary, you can use the initializer syntax:

var dictionaryName: [KeyType: ValueType] = [:]

Initialization:

  • Empty Dictionary:
var namesOfIntegers: [Int: String] = [:]
  • Dictionary with Initial Values:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Dictionary Operations:

  • Add a New Item:
airports["LHR"] = "London Heathrow"
  • Update a Value:
airports["LHR"] = "London Heathrow International"
  • Retrieve a Value:
let airportName = airports["LHR"]
  • Remove an Item:
airports["DUB"] = nil
  • Get the Number of Items:
let numberOfAirports = airports.count
  • Check if Dictionary is Empty:
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
  • Iterate Over a Dictionary:
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}

Important Methods and Properties:

  • keys: Retrieves an array of all the keys.
  • values: Retrieves an array of all the values.
  • removeValue(forKey:): Removes a key-value pair by its key and returns the value.
  • merge(_:uniquingKeysWith:): Merges two dictionaries.

Conclusion:

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.

  1. 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]
      
  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
      
  3. 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")
      
  4. 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)")
      }
      
  5. 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 }
      
  6. 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)
      
  7. 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)")
      }
      
  8. 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")