Swift - Creating an Empty Dictionary

Introduction

In Swift, you can create an empty dictionary of a specific data type using the initializer syntax, like this:

var months = Dictionary<Int, String>()

The preceding example creates an empty dictionary of Int key type and String value type.

To populate the dictionary, specify the key and its corresponding value:

months [1] = "January"
months [2] = "February"
months [3] = "March"
months [4] = "April"
months [5] = "May"
months [6] = "June"
months [7] = "July"
months [8] = "August"
months [9] = "September"
months [10] = "October"
months [11] = "November"
months [12] = "December"

To make months an empty dictionary again, assign it to a pair of brackets with a colon within it:

months = [:]

Related Topic