Swift: Creating an Empty Dictionary

Creating an Empty Dictionary in Swift:

We can create dictionaries that have no key-value pairs in them. An empty dictionary in Swift is a dictionary that has no key-value pairs.

When we want to populate our dictionary later, we can use this option.

For example, we can make a dictionary to keep track of the names and phone numbers of our personal contacts. Until we get the phone numbers of our contacts and save those key-value pairs, our dictionary will most likely be empty.

We can make an empty dictionary by using the following empty dictionary literal syntax:

var nameofDictionary: [KeyType: ValueType] = [:]

  • The data type of the keys and values must be declared.
  • We use [:] after the assignment operator = to declare that the dictionary is empty.

We can also use the initializer syntax to create an empty dictionary:

var nameofDictionary = [KeyType: ValueType]()

  • After the assignment operator, we declare the key and value types.
  • After declaring the data types, we add parentheses ().

There is no significant difference between these two approaches. While Swift’s Documentation uses initializer syntax to declare an empty dictionary, using one method over the other has no consequences.

Let’s make an empty dictionary with Int type keys and Int type values called Persons.

The following is the literal syntax for an empty dictionary:

var Persons: [Int: Int] = [:] ;

Syntax for initializers:

var Persons = [Int: Int]() ;

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: