We can create dictionaries that are initialized without any key-values pairs in it. A dictionary with no key-value pairs is also known as an empty dictionary.
This option is useful when we want to populate our dictionary at a later time.
For instance, we can create a dictionary that keeps track of the names of our personal contacts and their phone numbers. Very likely, our dictionary will start off empty until we get the phone numbers of our contacts and save those key-value pairs.
We can create an empty dictionary using empty dictionary literal syntax like this:
var dictionaryName: [KeyType: ValueType] = [:]
- We need to declare the data type of the keys and the values.
- After the assignment operator
=
, we use[:]
to declare it’s an empty dictionary.
We can also create an empty dictionary using initializer syntax:
var dictionaryName = [KeyType: ValueType]()
- We declare the key and value type after the assignment operator.
- We add parentheses
()
after declaring the data types.
Is there a major difference between these two methods? The answer is no! While Swift’s Documentation uses initializer syntax to declare an empty dictionary, there are no consequences of using one method over the other.
Let’s create an empty dictionary called yearlyPopulation
that contains Int
type keys and Int
type values.
Empty dictionary literal syntax:
var yearlyPopulation: [Int: Int] = [:]
Initializer syntax:
var yearlyPopulation = [Int: Int]()
Instructions
Declare an empty dictionary called emptyLiteral
with String
type keys and Int
type values using dictionary literal syntax.
Declare an empty dictionary called emptyInitializer
with String
type keys and Bool
type values using initializer syntax method.