我有一系列颜色,但数组中的元素数量可以改变。例如,我可以在第二天使用1种颜色但在第二天使用3种颜色。如何迭代数组,然后将元素添加到空字典?
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?
}
答案 0 :(得分:2)
要解决此问题,请尝试使用此方法:
for color in colors{
colorDict["someKey"] = color
}
正如您所看到的,您应首先为该密钥分配一些密钥和值。
在我的情况下,键是“someKey”和数组中的值颜色。
如果您没有明确的钥匙数量。枚举数组项的索引。
for (index, element) in colors.enumerate() {
colorDict[String(index)] = element
}