嘿伙计们,我是学习快速的初学者。在我的程序中,我有一个包含 49 个项目的数组,我想通过滑动动作(从左到右和从右到左)在屏幕上逐个打印出每个项目。但是,当我到达数组的末尾时,由于数组索引范围超出,我遇到了致命错误
。
我试图使用一个计数器变量来计算滑动次数,并在达到49时将其索引号设置为0,但它不起作用。我该如何应对这个?谢谢。
if swipeCounter == 49{
swipeCounter = 0
}
firstCell.text = String(numberList[swipeCounter])
secondCell.text = String(numberList[swipeCounter + 1])
thirdCell.text = String(numberList[swipeCounter + 2])
swipeCounter = ++swipeCounter
println(swipeCounter)
发生错误可能是因为您正在检查swpe
我建议你这样做
firstCell.text = String(numberList[swipeCounter % numberList.count])
secondCell.text = String(numberList[(swipeCounter + 1) % numberList.count])
thirdCell.text = String(numberList[(swipeCounter + 2) % numberList.count])
模运算符应该只处理任何索引溢出,如果数组长度发生变化,用 numberList.count 替换 49 也将是一个不错的举动。
希望这有所帮助!