Dictionary has for keyValue an array of class

Hello everyone,

I am new in this Forum and I would like to be active in it in order to help and be helped.


My problem is this one :

I have to create a Dictionary in Xcode that has a Key Value (type : String) and the associated value is an Array of Class called 'Food', practically it is an Array of instances of that type of class. In particular this Class has only one property, that is the name (String).


class Food  {
    var name : String
}

I have to set the Dictionary in order to assign to every key value (for example "sweet", "meat" and "fish") the determined Array of type 'Food' that will contain all the possible istances of the Classes Food with already set the name of them

I don't know how to implement this concept inside the code.

I've tryed in this way :

var foodlist = [String : [Food]] ()


Then I don't know how to instantiate the different cell of the array Food for every key value.

I try to do this in my own way but It always doesn't work. He returns Errors, so surely is written in a wrong way

You're on the right track. Because you have a dictionary of arrays, you will need 2 loops to enumerate all of the array elements.


To enumerate the dictionary elements, your code would look like this:


     for (foodType, foods) in foodlist {
          …
     }


That's because dictionary enumerations return both the key and the value. Within the loop, you need to enumerate each food within the (current) "foods":


     for (foodType, foods) in foodlist {
          for food in foods {
               // do something with "food"
          }
     }


Note that this enumerates every element of the array for every key. It does not instantiate (create) any Food objects. They must already exist and be in the dictionary.

Is that what you wanted to know?

Dictionary has for keyValue an array of class
 
 
Q