Swift: declare an empty dictionary

You can't use [:] unless type information is available.

You need to provide it explicitly in this case:

var dict = Dictionary<String, String>()

var means it's mutable, so you can add entries to it. Conversely, if you make it a let then you cannot further modify it (let means constant).

You can use the [:] shorthand notation if the type information can be inferred, for instance

var dict = ["key": "value"]

// stuff

dict = [:] // ok, I'm done with it

In the last example the dictionary is known to have a type Dictionary<String, String> by the first line. Note that you didn't have to specify it explicitly, but it has been inferred.


The Swift documentation recommends the following way to initialize an empty Dictionary:

var emptyDict = [String: String]()

I was a little confused when I first came across this question because different answers showed different ways to initialize an empty Dictionary. It turns out that there are actually a lot of ways you can do it, though some are a little redundant or overly verbose given Swift's ability to infer the type.

var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()

After you have an empty Dictionary you can add a key-value pair like this:

emptyDict["some key"] = "some value"

If you want to empty your dictionary again, you can do the following:

emptyDict = [:]

The types are still <String, String> because that is how it was initialized.


var emptyDictionary = [String: String]()

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

Note: if you're planning to change the contents of the dictionary over time then declare it as a variable (var). You can declare an empty dictionary as a constant (let) but it would be pointless if you have the intention of changing it because constant values can't be changed after initialization.