Swift: declare an empty dictionary


In Swift, there are some different syntaxes to declare an empty dictionary. It is important to remember that all syntaxes produce the same result. In this article, you will see examples of how to declare an empty dictionary and define a dictionary in Swift.

What is a Swift Dictionary?

A dictionary is a collection in Swift that lets you keep key-value pairs. Each key in the dictionary has a corresponding value, and each word in the dictionary needs to be distinct. Because dictionaries are unordered, the sequence in which key-value pairs are introduced does not matter.

Example

In this example, we create a dictionary with three key-value pairs. The keys are "apple", "banana", and "orange", and the corresponding values are 1, 2, and 3. Also, we can access dictionary values using their corresponding keys.

Here's an example of a simple dictionary in Swift −

import Foundation

// define a dictionary
var dictionary = ["apple": 1, "banana": 2, "orange": 3]
print("Original Dictionary: \(dictionary)")

// access the elements
print(dictionary["apple"] ?? 0)
print(dictionary["banana"] ?? 0)

// adds a new key-value pair
dictionary["pear"] = 4

// removes the key-value pair with key "banana"
dictionary.removeValue(forKey: "banana")

// modifies the value for the key "apple"
dictionary["apple"] = 5
print("Updated Dictionary: \(dictionary)")

Output

Original Dictionary: ["banana": 2, "apple": 1, "orange": 3]
1
2
Updated Dictionary: ["pear": 4, "orange": 3, "apple": 5]

Overall, dictionaries provide a convenient way to store and retrieve data associated with a specific key. This makes it a powerful tool for organizing and manipulating data in your Swift programs.

Here are a few more examples of how to declare an empty dictionary in Swift

Example 1: Dictionary with String keys and Any Values

var dictionary = [String: Any]()

In this example, we declare an empty dictionary with String keys and Any values. This means that we can add any type of value to the dictionary, including strings, numbers, arrays, and other dictionaries.

Example 2: Dictionary with Int keys and String Values

var dictionary = [Int: String]()

Here, we declare an empty dictionary with Int keys and String values. This is useful when we want to store a list of items that can be accessed by an index, such as an array.

Example 3: Dictionary with Custom object keys and Values

import Foundation
class Person: Hashable {
   var name: String
   var age: Int
    
   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
    
   static func == (lhs: Person, rhs: Person) -> Bool {
      return lhs.name == rhs.name && lhs.age == rhs.age
   }
    
   func hash(into hasher: inout Hasher) {
      hasher.combine(name)
      hasher.combine(age)
   }
}
var dictionary = [Person: Int]()
print(dictionary)

Output

[:]

In this example, we declare an empty dictionary with custom object keys and Int values. This allows us to store values that are associated with a specific instance of a custom class called Person. Note that the custom class Person needs to conform to the Hashable protocol in order to be used as a dictionary key as shown in the above example.

Because dictionaries offer a handy way to keep and access information connected to a particular key, they are a crucial data structure in programming, including Swift. The following are some key advantages of utilizing a dictionary in your Swift programs −

  • Effective lookups − Even when you have a lot of data, dictionaries let you look up numbers rapidly using their corresponding keys. This is due to the fact that dictionaries employ a hash table algorithm, which enables constant time (O(1)) lookups.

  • Key-value combinations in dictionaries make it simple to organize data in a way that is both understandable and manipulative. When dealing with complicated data sets or data with a hierarchical structure, this can be particularly helpful.

  • Flexibility − Swift dictionaries are changeable and capable of storing any kind of information, including custom objects and data from other dictionaries. They are therefore flexible for managing and organizing data in your programs.

  • Code readability can be improved by using dictionaries to hold data, particularly if you use descriptive keywords that clarify the meaning of the data.

  • Effective management of data relationships − Dictionaries offer a means of expressing the connections between various data sets. To keep informed about the parts of a vehicle, for instance, you might use a dictionary where the keys are the titles of the parts and the values are specifics like their height, weight, and material.

Conclusion

In conclusion, dictionaries are an important data structure in Swift programming. They provide a convenient way to store and retrieve data that is associated with a specific key, making it a powerful tool for organizing and manipulating data in your programs. Dictionaries offer benefits such as efficient lookups, easy organization of data, flexibility, improved code readability, and effective handling of data relationships. Therefore, it is essential to learn how to use dictionaries effectively to build robust and efficient Swift programs.

Updated on: 04-May-2023

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements