Swift declare an empty dictionary
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. One of the essential data structures in Swift is the dictionary, which stores associations between keys and values. This article focuses on how to declare an empty dictionary in Swift, along with technical explanations and examples to better understand its usage.
Declaring an Empty Dictionary in Swift
In Swift, dictionaries are unordered collections that map keys to values. Both keys and values can be of any type that conforms to the Hashable protocol for keys and any type for values. Let's explore how to declare an empty dictionary in Swift.
Explanation
- Type Annotation: The syntax
[String: Int]explicitly states the dictionary's key and value types. The variableemptyDictis initialized with an empty literal[:]indicating an empty dictionary. - Type Inference: Swift's type inference allows you to omit specifying the types explicitly if the variable's type can be inferred from its initial value. The
anotherEmptyDictis inferred as a dictionary withStringkeys andIntvalues from the context provided by the initialization. - Dictionary Initializer: Swift provides a generic
DictionaryinitializerDictionary<Key, Value>()to create an empty dictionary.yetAnotherEmptyDictis another example of creating an empty dictionary by specifying types explicitly using theDictionaryinitializer.
Key Points Summary
Below is a table summarizing the key points of declaring an empty dictionary in Swift.
| Method | Syntax | Description |
| Type Annotation | var dict: [KeyType: ValueType] | Specifies the key and value types explicitly using colons and initializes with an empty literal. |
| Type Inference | var dict = [KeyType: ValueType]() | Leverages Swift's type inference without explicitly mentioning types. |
| Dictionary Initializer | var dict = Dictionary<KeyType, ValueType>() | Uses the Dictionary initializer to declare an empty dictionary. |
Subtopics
When to Use Dictionaries
Dictionaries are suitable for scenarios where you need to look up values based on identifier keys. Use them when:
- You have a set of unique keys mapped to corresponding values.
- Order does not matter between the key-value pairs.
- You wish to perform constant-time lookups (given a good hash function).
Performance Considerations
Swift's dictionaries are optimized for performance, with an average time complexity of for lookup, insertion, and deletion when operations are performed randomly distributed over the key space.
Safety and Type Constraints
Swift dictionaries exhibit type safety and compile-time type-checking. You must provide conforming types for both keys and values to avoid runtime errors. Remember that keys must adopt the Hashable protocol, ensuring they have a unique hash value for indexing purposes.
Mutability
Swift dictionaries are mutable when declared with var and immutable when declared with let. This is useful for controlling state and ensuring thread safety where necessary.
Examples of Adding Entries
Once you've declared an empty dictionary, you might want to add entries:
In the example above, contactList starts as an empty dictionary of type [String: String] and later has two key-value pairs added to it.
Conclusion
Dictionaries in Swift are a versatile and efficient way to manage key-value pairs. Being familiar with different ways to initialize an empty dictionary is fundamental for any Swift developer. Understanding when and why to use dictionaries, along with grasping the nuances of their syntax and performance characteristics, will enable you to harness their full potential effectively in your projects.
Related reading
- Swift declare an empty dictionary
- Swift delete all array elements
- Swift delete all array elements
- Swift Dictionary Get values as array
- Swift default AlertViewController breaking constraints
- Swift Determine iOS Screen size
- Swift JSONDecode decoding arrays fails if single element decoding fails
- Swift Pass array by reference?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.