208

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?

Juan Boero
  • 6,281
  • 1
  • 44
  • 62
z22
  • 10,013
  • 17
  • 70
  • 126
  • 4
    weird, I get no error doing this, I can even ask for the count and the playground gives me 0. – Kaan Dedeoglu Jun 04 '14 at 09:20
  • mine doesnt give any compiler error even from runtime I can get a println of the constants & they just print this in console `array :() dictionary :{}` print statements `let arr = [] let dict = [:] println("array :\(arr)") println("dictionary :\(dict)")` – nsuinteger Jun 04 '14 at 09:35
  • [Check this link](http://stackoverflow.com/a/33151885/1634890) – Juan Boero Mar 30 '16 at 14:18
  • https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105 – ma11hew28 Jun 04 '16 at 19:04

19 Answers19

360
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.

damirstuhec
  • 6,069
  • 1
  • 22
  • 39
  • 1
    You can declare empty array as a constant but it is pointless. If you read the docs, you can see that an array is always declared as ``var`` as I suggested you: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html – damirstuhec Jun 04 '14 at 11:06
  • 1
    var emptyDict:NSMutableDictionary = [:] – Jio Jun 27 '14 at 08:48
44

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.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Of the many options available in Swift, my favourite syntax for a simple String/String dict is:`var dict: [String: String] = [:]` – Dawngerpony Dec 11 '14 at 12:30
  • Thank you!. Dictionary() fixed my problem, I had actually a dictionary from Enum to MyClass. What do you mean by "type information is available"? – Eduardo Reis May 11 '17 at 15:18
41

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • If you wanted to initialize an array of an empty dictionary, you'd do it as such: `var emptyDictArray = [[String: String]()]` `var emptyDictArray = [Dictionary()]` – Don Alejandro Oct 02 '15 at 19:14
19

Use this will work.

var emptyDict = [String: String]()
Lim Thye Chean
  • 8,704
  • 9
  • 49
  • 88
  • I prefer this one. Because we can declare an empty array by `var emtpyAry = [String]()`. That make sense. – hbin Aug 20 '14 at 02:11
16

You can simply declare it like this:

var emptyDict:NSMutableDictionary = [:]
Pang
  • 9,564
  • 146
  • 81
  • 122
Jio
  • 1,146
  • 1
  • 9
  • 22
8

Declaring & Initializing Dictionaries in Swift

Dictionary of String

var stringDict: [String: String] = [String: String]()

OR

var stringDict: Dictionary<String, String> = Dictionary<String, String>()

Dictionary of Int

var stringDict: [String: Int] = [String: Int]()

OR

var stringDict: Dictionary<String, Int> = Dictionary<String, Int>()

Dictionary of AnyObject

var stringDict: [String: AnyObject] = [String: AnyObject]()

OR

var stringDict: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()

Dictionary of Array of String

var stringDict: [String: [String]] = [String: [String]]()

OR

var stringDict: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()

Array of Dictionaries of String

var stringDict: [[String: String]] = [[String: String]]()

OR

var stringDict: Array<Dictionary<String, String>> = Array<Dictionary<String, String>>()
Syed Qamar Abbas
  • 3,637
  • 1
  • 28
  • 52
6

You have to give the dictionary a type

// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()

If the compiler can infer the type, you can use the shorter syntax

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
nevan king
  • 112,709
  • 45
  • 203
  • 241
5

Swift:

var myDictionary = Dictionary<String, AnyObject>()
Juan Boero
  • 6,281
  • 1
  • 44
  • 62
4

I'm playing with this too. It seems strange that you can just declare an empty dictionary and then add a key/value pair to it like so :

var emptyDictionary = Dictionary<String, Float>()
var flexDictionary = [:]
emptyDictionary["brian"] = 4.5
flexDictionary["key"] = "value" // ERROR : cannot assign to the result of this expression

But you can create a Dictionary that accepts different value types by using the "Any" type like so :

var emptyDictionary = Dictionary<String, Any>()
emptyDictionary["brian"] = 4.5
emptyDictionary["mike"] = "hello"
Lee Probert
  • 10,308
  • 8
  • 43
  • 70
4

You need to explicitly tell the data type or the type can be inferred when you declare anything in Swift.

Swift 3

The sample below declare a dictionary with key as a Int type and the value as a String type.

Method 1: Initializer

let dic = Dictionary<Int, String>()

Method 2: Shorthand Syntax

let dic = [Int:String]()

Method 3: Dictionary Literal

var dic = [1: "Sample"]
// dic has NOT to be a constant
dic.removeAll()
XY L
  • 25,431
  • 14
  • 84
  • 143
4

To create an empty dictionary with the [:] aka the empty dictionary literal, you actually need to provide the context first as in the type of both the key and the value. The correct way to use the [:] to create an empty dictionary is:

var dict: [String: Int] = [:]
3

If you want to create a generic dictionary with any type

var dictionaryData = [AnyHashable:Any]()
reetu
  • 313
  • 3
  • 11
3

Swift 4

let dicc = NSDictionary()

//MARK: - This is empty dictionary
let dic = ["":""]

//MARK:- This is variable dic means if you want to put variable 
let dic2 = ["":"", "":"", "":""]

//MARK:- Variable example
let dic3 = ["name":"Shakeel Ahmed", "imageurl":"https://abc?abc.abc/etc", "address":"Rawalpindi Pakistan"]

//MARK: - This is 2nd Variable Example dictionary
let dic4 = ["name": variablename, "city": variablecity, "zip": variablezip]

//MARK:- Dictionary String with Any Object
var dic5a = [String: String]()
//MARK:- Put values in dic
var dic5a = ["key1": "value", "key2":"value2", "key3":"value3"]

var dic5b = [String:AnyObject]()
dic5b = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]

or
//MARK:- Dictionary String with Any Object
let dic5 = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]

//MARK:- More Easy Way
let dic6a = NSDictionary()
let dic6b = NSMutalbeDictionary()
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34
2

I'm usually using

var dictionary:[String:String] = [:]
dictionary.removeAll()
0

You can declare it as nil with the following:

var assoc : [String:String]

Then nice thing is you've already typeset (notice I used var and not let, think of these as mutable and immutable). Then you can fill it later:

assoc = ["key1" : "things", "key2" : "stuff"]
newshorts
  • 1,057
  • 12
  • 12
0

You can use the following code:

var d1 = Dictionary<Int, Int>()
var d2 = [Int: Int]()
var d3: Dictionary<Int, Int> = [Int : Int]()
var d4: [Int : Int] = [:]
levan
  • 440
  • 1
  • 8
  • 19
-2

var dictList = String:String for dictionary in swift var arrSectionTitle = String for array in swift

Gaurav
  • 553
  • 5
  • 9
-2
var parking = [Dictionary < String, Double >()]

^ this adds a dictionary for a [string:double] input

itsji10dra
  • 4,603
  • 3
  • 39
  • 59
wildCard
  • 51
  • 6
-3

It is very handy for finding your way

var dict:Dictionary = [:]

Uttam Kumar
  • 169
  • 1
  • 8