如果数组在最后,如何遍历数组并重新启动?

Cas*_*ert 0 arrays ios swift

我有一系列颜色,我想uitableviewcells在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]
Run Code Online (Sandbox Code Playgroud)

问题是,当indexPath.rowcolorCalet数组大于colorPalet数组时,它会崩溃,因为数组中没有更多的条目.如果它在Swift中的数组末尾,如何再次通过数组启动iteratie?

ROC*_*ROC 5

你可以使用modulo:

cell.backgroudColor = colorPalet[indexPath.row % colorPalet.count]
Run Code Online (Sandbox Code Playgroud)