Caspert Caspert - 2 months ago 13
iOS Question

How to loop through array and start again if the array is at the end?

I have an array of colors, that I want to apply to

in iOS.

let colorPalet = [
UIColor(red: 255.0/255.0, green: 159.0/255.0, blue: 112.0/255.0, alpha: 1),
UIColor(red: 81.0/255.0, green: 218.0/255.0, blue: 168.0/255.0, alpha: 1),
UIColor(red: 2.0/255.0, green: 207.0/255.0, blue: 255.0/255.0, alpha: 1),
UIColor(red: 144.0/255.0, green: 153.0/255.0, blue: 166.0/255.0, alpha: 1)
cell.backgroundColor = colorPalet[indexPath.row]

The problem is, then when
is greater then the colorPalet array, it will crash, because there is no more entries in the array. How to start iteratie again through the array if it is at the end of the array in Swift?


you can use modulo:

cell.backgroudColor = colorPalet[indexPath.row % colorPalet.count]