arrays - 迭代数组并将元素添加到 Swift 2.2 中的空字典

标签 arrays swift for-loop dictionary

我有一个颜色数组,但数组中元素的数量可以改变。例如,我可能 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/

相关文章:

c - 在结构中的 scanf 中使用 char 时遇到问题

javascript - 如何映射嵌套对象数组?

c - c中字符数组结束后会发生什么?

ios - Swift:在 View 之间传递变量而不是第一次更新

javascript - 随机生成的数字 - "Check"函数

javascript - 理解 javascript 中的 for 循环

ios - 使用选择器为 UItapgestureRecognizer 传递额外参数

python - 在 Python 循环中构建字典 - 列表和字典理解

c++ - 为什么这个 for 循环不正确?

swift - "dyld: Library not loaded' , "reason: Image not found"错误在 Swift 2.2 iOS with watch