0

I have a dictionary like this:

  var dict=
    [  "attractions"   : ["ALL" : [], "BY TYPE": []],
       "accommodation" : ["ALL" : [] ] 
    ]

And I want to take dynamically the keys and values of this dictionary.

For example I want to take the second key so accommondation and then check how many keys does this has so 1 and print them. Finally I want to take the value of a specific key for example I want to take the array of the by type key (dynamically), so I want something like

dict[0][1]

I found from another question this extension (in swift 2 and I converted in swift 3 so maybe it's not even right) but I can't understand how to use it.

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)]
        }
    }
}

Thanks in advance.

mike vorisis
  • 2,786
  • 6
  • 40
  • 74
  • 2
    I'd avise against such usage - this may lead someone reading your code (note that this someone may also be yourself in some time) to believe that this is either an `Array` or a dictionary with numbers as keys. What is your aim in this? Why would you need this? – Losiowaty Apr 14 '17 at 14:10
  • 6
    A dictionary has no defined order, so subscripting doesnt make sense. – Paulw11 Apr 14 '17 at 14:11
  • @Losiowaty I will use it as when i tap a cell i will check which row it is and in another view i will generate as many buttons as this key has (so for the first key I will have 2 buttons) and then I will check which button the user tapped and if the array is empty i will execute a function or if its not empty I'll generate as many buttons as the count of the array – mike vorisis Apr 14 '17 at 14:16
  • I have something on my mind of what can I do but I was curious if I could do it with a dictionary and not with multiple arrays etc – mike vorisis Apr 14 '17 at 14:17
  • @Paulw11 do you mean that the order of the keys may be changed after I launch the app? – mike vorisis Apr 14 '17 at 14:28
  • 1
    @mikevorisis the same exact dict _might_ have the keys in the same order, but there is no guarantee of the that at all. Adding just one key could completely change the order -- there is just no order specification at all on dictionaries. Even if you check this and dicts seem to have stable key order, you are still counting on undefined behavior. See http://stackoverflow.com/questions/30969688/ordered-dictionary-in-swift for alternative structures – Lou Franco Apr 14 '17 at 14:33
  • @LouFranco thanks for your comment I'm gonna try your suggestion – mike vorisis Apr 14 '17 at 14:44

0 Answers0