Swift 循环。for-in

117 阅读1分钟

本教程属于Swift系列

for-in 循环可以用来迭代特定数量的次数,使用范围操作符。

for index in 0...3 {
  //iterate 4 times, `index` is: 0, 1, 2, 3
}

你可以在一个数组或集合的元素上进行迭代。

let list = ["a", "b", "c"]
for item in list {
  // `item` contains the element value
}

以及在一个字典的元素上。

let list = ["a": 1, "b": 2, "c": 2]
for (key, value) in list {
  // `key` contains the item key
  // `value` contains the item value
}