我有一个颜色数组,但数组中元素的数量可以改变。例如,我可能 1 天有 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?
}
最佳答案
为了解决问题,请尝试使用这种方法:
for color in colors{
colorDict["someKey"] = color
}
如您所见,您应该首先分配一些键,然后为该键分配值。
在我的例子中,键是“someKey”,值是数组中的颜色。
如果您没有明确数量的 key 。用数组项的索引枚举。
for (index, element) in colors.enumerate() {
colorDict[String(index)] = element
}
关于arrays - 迭代数组并将元素添加到 Swift 2.2 中的空字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39372868/