hidexh
hidexh

Reputation: 13

How to access values from nested Dictionaries: Swift

Quick question. Lets say for instance that I want to create a data model for the following:

A list that populates with grocery stores that I go to, and then stores a date each time I go to any given grocery store, and within each date entry it stores the items that I purchased.

For example:

             Costco -> June 1, 2016 -> Water
                                    -> Beer

                    -> June 8, 2016 -> Hot dogs
                                    -> Chips

             Target -> June 1, 2016 -> Dish Soap
                                    -> Shampoo

                    -> June 8, 2016 -> Bananas
                                    -> Bagels

How best would I arrange this into a data model?

Is it possible to start with the following?:

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

Using this dictionary inside a dictionary, I can't figure out how to access the array under any given "Grocery store -> Date" profile.

Disclaimer: I'm very new to Swift so forgive the ignorance. I have read Apple's documentation on dictionaries and it didn't help.

Upvotes: 1

Views: 1280

Answers (1)

TheBrownCoder
TheBrownCoder

Reputation: 1226

Yes, having a dictionary of dictionaries is definitely possible (though at that point you might want to consider using a class or struct instead).

You could initialize it using: var dataModel = [String: [String: [String]]]()

Accessing it would like something like this:

dataModel["Costco"]?["June 1, 2016"] //returns an optional of type String

That accessor

Though again, I would definitely recommend you look into creating a struct to encapsulate this data. With a struct, you could create your own GroceryStore struct to use as a key and you could use proper NSDate objects as keys for the second layer.

Best of luck and let me know if you have any questions!

Upvotes: 2

Related Questions