How to start from the beginning when you reached end of index of array range in swift? -
How to start from the beginning when you reached end of index of array range in swift? -
hey guys i'm beginner of learning swift. in programme have array has 49 items , want print out labels every item 1 1 on screen swiping action (left right , right left). when reach end of array fatal error
because of out array index range.
i tried utilize counter variable in order count swipes , set index number 0 when reaches 49 not work. how can cope 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)
the error occurring because checking value of swipecounter , increasing it. if swipecounter
48, not set 0 , effort access swipecounter + 2
i.e. 50 result in crash. plus not big fan of using hardcoded lengths in code.
i 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 handle index overflows , replacing 49 numberlist.count move if array length changes.
hope helps!
arrays swift
Comments
Post a Comment