labnxx labnxx - 11 months ago 64
Swift Question

Iterate over Array and add element to empty dictionary in Swift 2.2

I have an array of colors but the number of elements in the array can change. For example I may have 1 color 1 day but 3 colors the next day. How can I iterate over the array and then add the elements to an empty dictionary?

var colors = [String]()
var colorDict = [String: AnyObject]()

//day1 the array has 2 colors
self.colors = ["red", "blue"]

//day2 the array has 3 colors
self.colors = ["red", "blue", "orange"]

//day3 the array has 1 color
self.colors = ["blue"]

//regardless of which day it is I need to iterate over the array and add whatever is inside to the dictionary
for color in self.colors{
//how would I add elements to self.colorDict?

Answer Source

For solving of the issue try to use this approach:

for color in colors{
    colorDict["someKey"] = color

As you can see you should firstly assign some key and than value for that key.

In my case key is "someKey" and value color from array.

If you do not have clear amount of keys. Enumerate with index of the array item.

for (index, element) in colors.enumerate() {
     colorDict[String(index)] = element