【问题标题】:How do I iterate three or more arrays in the same Swift loop?如何在同一个 Swift 循环中迭代三个或更多数组?
【发布时间】:2018-05-02 10:54:19
【问题描述】:

迭代一个数组:

for item in myArray {
    print(item)
}

迭代两个数组:

for (item1, item2) in zip(myArray1, myArray2) {
    print(item1, item2)
}

但是三个或更多数组呢?

【问题讨论】:

  • 你的数组长度都一样吗?
  • 是的,他们是:)

标签: arrays swift loops zip


【解决方案1】:

你可以这样用,下面是2个数组

zip([11,12,12], [12,13,14]).forEach { (i1, i2) in
    print(i1, i2)
}

如果数组长度相同,你可以使用这个,简单的方法

for index in 0...firstArray.count {
    print(firstArray[index]) //First Array
    print(secondArray[index]) //Second Array
    print(thirdArray[index]) //Third Array
}

另一种解决方法是这样的,

for index in firstArray.enumerated() {
    print(firstArray[index]) //First Array
    print(secondArray[index]) //Second Array
    print(thirdArray[index]) //Third Array
}

【讨论】:

  • 太棒了!第二个是为我做的!非常感谢您的帮助和抽出时间。这肯定有助于优化我的代码:)
猜你喜欢
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 2015-04-04
相关资源
最近更新 更多