-7

I was wondering that in the following case:

var array = ["1":["First whatever","Second whatever"],"2":["Third whatever", "Forth whatever"]]

a) How do I access "Second whatever" in other words how do I return "Second whatever"

b) How do I access "2"

If these are even possible.

Edit1: The code wasn't correct. Here is the correct one:

var arrays: [[String:[String]]] = [["1":["First whatever","Second whatever"]],["2":["Third whatever", "Forth whatever"]]]

And to get "Second whatever" I tried this:

arrays[0][1]
Kocsis Kristof
  • 74
  • 2
  • 10
  • Possible duplicate of [how can i get key's value from dictionary in Swift?](http://stackoverflow.com/questions/25741114/how-can-i-get-keys-value-from-dictionary-in-swift) – brimstone Jun 05 '16 at 17:06
  • Use NSArray in order to acsess the whole array and NsDictionary for every individual object – Cloy Jun 05 '16 at 17:14
  • https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105 – Eric Aya Jun 05 '16 at 19:01

1 Answers1

4

This data structure is very difficult to deal with. I would consider if this is the best way to store this data. Maybe an array of structs that represent your data?

The confusing part is your variable is named array, but it is really declared as a Dictionary literal. So to access the item with key "1" in array looks like this:

let dictionaryEntry = array["1"]   

...which is going to return an optional array of strings "First Whatever", "Second Whatever" - because there is no guarantee it will find "1" in the dictionary.

The dictionary contains an Array of Strings, so to get a single value, for example the 2nd value in the String Array, it would be:

let  dict = array["1"]?[1]  //returns "Second Whatever" as an optional

Again, this is how you access the items in your collection, but I'd strongly review how the data is being stored.

DJohnson
  • 929
  • 4
  • 15