Reputation: 13
Hey guys I'm a beginner of learning swift. In my program I have an array which has 49 items and I want to print out by labels every item one by one on screen by swiping action (left to right and right to left). However when I reach the end of my array I get fatal error
because of out array index range.
I tried to use a counter variable in order to count swipes and set its index number to 0 when it reaches 49 but it does not work. How can I cope with this? Thanks.
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)
Upvotes: 0
Views: 504
Reputation: 2994
The error is probably occurring because you are checking the value of swipeCounter and then increasing it. So even if swipeCounter
is 48, it will not be set to 0 and an attempt to access swipeCounter + 2
i.e. 50 will result in a crash. Plus I am not really a big fan of using hardcoded lengths in my code.
I would suggest doing this
firstCell.text = String(numberList[swipeCounter % numberList.count])
secondCell.text = String(numberList[(swipeCounter + 1) % numberList.count])
thirdCell.text = String(numberList[(swipeCounter + 2) % numberList.count])
the modulus operator should just handle any index overflows and replacing 49 with numberList.count will also be a good move if the array length changes.
Hope this helps!
Upvotes: 1