Initialising empty arrays of dictionaries in Swift Initialising empty arrays of dictionaries in Swift arrays arrays

Initialising empty arrays of dictionaries in Swift


You need to give types to the dictionaries:

var myNewDictArray: [Dictionary<String, Int>] = []

or

var myNewDictArray = [Dictionary<String, Int>]()

Edit: You can also use the shorter syntax:

var myNewDictArray: [[String:Int]] = []

or

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


This will create an empty, immutable dictionary:

let dictionary = [ : ]

And if you want a mutable one:

var dictionary = [ : ]

Both of these dictionaries default to Dictionary<String?, AnyObject?>.


The reason this isn't working:

var myNewDictArray: Dictionary[] = []

is that you need to provide types for the keys and values of a dictionary when you define it. Each of these lines will create you an empty array of dictionaries with string keys and string values:

var dictArray1: Dictionary<String, String>[] = Dictionary<String, String>[]()var dictArray2: Dictionary<String, String>[] = []var dictArray3 = Dictionary<String, String>[]()