user5130344
user5130344

Reputation:

iOS Dictionary with two values per key?

I currently have a dictionary that contains 1 value per key. Is it possible to have 2 values per key?

 var data = HomeVC.getData()
 MyVariables.users = data.users;
 MyVariables.img = data.img;

//MY Current dictionary with 1 value and 1 key
   for (index, element) in enumerate(MyVariables.users) 
{
   MyVariables.dictionary[element as! String] = MyVariables.img[index]
}

I'm trying to add values from another array to this dictionary. So in total I would have 3 arrays in the same index position when calling them. 2 values and 1 key

Upvotes: 3

Views: 2622

Answers (3)

Shamas S
Shamas S

Reputation: 7549

Instead of that try saving an NSArray as the value for key. The NSArray will be able to save more than 1 values and should suffice.

The lifecycle for a 2 values per key would look something like this

myDict[@"key1"] = value1;
// then set next value
myDict[@"key1"] = value2;

Now your dictionary has lost the first value and you only have access to the last one.

Your code would look something like

   for (index, element) in enumerate(MyVariables.users) 
{
   var savedArray: [Your-Object-Type-Here]? = []
   var savedArray = MyVariables.dictionary[element as! String]
   if savedArray != nil {
       savedArray!.append(MyVariables.img[index])
   }
   else {
      savedArray = []
   }
   MyVariables.dictionary[element as! String] = savedArray
}

Upvotes: 3

kelin
kelin

Reputation: 11974

You can use arrays or tuples as values of a dictionary:

var dictionary: Dictionary<String, (ValType1, ValType2)>
dictionary["foo"] = (bar, baz)
println(dictionary["foo"][1])

Upvotes: 6

Phillip Mills
Phillip Mills

Reputation: 31016

If your values are different types, create a custom class to hold the values. Make your dictionary keys point to objects of your custom class.

Upvotes: 2

Related Questions