Iterate over Array and add element to empty dictionary in Swift 2.2 -
i have array of colors number of elements in array can change. example may have 1 color 1 day 3 colors next day. how can iterate on array , add elements empty dictionary?
var colors = [string]() var colordict = [string: anyobject]() //day1 array has 2 colors self.colors = ["red", "blue"] //day2 array has 3 colors self.colors = ["red", "blue", "orange"] //day3 array has 1 color self.colors = ["blue"] //regardless of day need iterate on array , add whatever inside dictionary color in self.colors{ //how add elements self.colordict? }
for solving of issue try use approach:
for color in colors{ colordict["somekey"] = color }
as can see should firstly assign key , value key.
in case key "somekey" , value color array.
if not have clear amount of keys. enumerate index of array item.
for (index, element) in colors.enumerate() { colordict[string(index)] = element }
Comments
Post a Comment