Swift: declare an empty dictionary

z22 picture z22 · Jun 4, 2014 · Viewed 201k times · Source

I am beginning to learn swift by following the iBook-The Swift Programming Language on Swift provided by Apple. The book says to create an empty dictionary one should use [:] same as while declaring array as []:

I declared an empty array as follows :

let emptyArr = [] // or String[]()

But on declaring empty dictionary, I get syntax error:

let emptyDict = [:]

How do I declare an empty dictionary?

Answer

damirstuhec picture damirstuhec · Jun 4, 2014
var emptyDictionary = [String: String]()

­

var populatedDictionary = ["key1": "value1", "key2": "value2"]

Note: if you are going to change the contents of the dictionary over time then declare it as a var (variable). You can declare an empty dictionary as a let (constant) but it is pointless if you have the intention of changing its contents over time, since constant can't be changed after it has been initialized.


Old answer:

Creating an empty dictionary of type <String, String> would look as follows:

var emptyDictionary = Dictionary<String, String>()