【问题标题】:How to start from the beginning when you reached end of index of array range in swift?当您快速到达数组范围索引的末尾时,如何从头开始?
【发布时间】:2014-12-25 03:05:24
【问题描述】:

大家好,我是学习 swift 的初学者。在我的程序中,我有一个包含 49 个项目的数组,我想通过滑动操作(从左到右和从右到左)在屏幕上一个一个地打印每个项目的标签。但是,当我到达数组末尾时,由于超出数组索引范围,我得到fatal error

我尝试使用计数器变量来计算滑动次数,并在达到 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)

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    错误可能是因为您正在检查 swipeCounter 的值然后增加它。因此,即使swipeCounter 为 48,它也不会设置为 0,并且尝试访问 swipeCounter + 2 即 50 将导致崩溃。另外,我不太喜欢在我的代码中使用硬编码长度。

    我建议这样做

    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 也是一个不错的举措。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      相关资源
      最近更新 更多