iPhoneDeveloper
iPhoneDeveloper

Reputation: 996

Swift : How do i create an array of dictionaries, where each dictionary contains an array inside them?

I am trying to load some data from my plist into an array. While declaring an array i did something like this

var natureList : [Dictionary] = [] as! [Dictionary]

I am getting this error enter image description here

Here is my plist file enter image description here

So how do i declare an array to load this data from my plist. ? I know its simple but this small thing is eating my head. Any help appreciated.

Upvotes: 3

Views: 7201

Answers (2)

theMikeSwan
theMikeSwan

Reputation: 4729

Ahmad F has the right answer, but just in case you (or a future reader) need to be more specific at some point here is how to break it down to a super specific type…

The inner most items in the plist (Summary: 1st flower, etc.) are all [String: String] because the key is a string and so is the associated value.

All of those inner most dictionaries are held in arrays so we add an extra set of brackets around our previous type: [[String : String]].

Moving up a level all of those arrays are in a dictionary which means we add the key type, colon, and brackets: [String: [[String : String]]]

The dictionaries from the previous step are all held in an array which means we add another set of brackets to the outside leaving us with: [[String: [[String : String]]]].

Again this level of detail is likely overkill but it is useful for demonstrating one way of breaking down a complex data structure by starting at the innermost level and working your way out. There are other ways of breaking down a structure like this but this one is highly effective.

Upvotes: 0

Ahmad F
Ahmad F

Reputation: 31645

It should be declared as follows:

var natureList = [[String: Any]]()

or as @LeoDabus advised (thanks to him):

var natureList: [[String: Any]] = []

Means that natureList is an array of dictionaries of strings as keys and any as values.

If you are aiming to declare it using Dictionary -which is uanessacry-, you could also do it like this:

var natureList = [Dictionary<String, Any>]()

Upvotes: 9

Related Questions