如何计算数组的正确索引

时间:2017-03-08 14:24:47

标签: arrays swift math

我已经实现了一个tableView,其工作方式类似于下面的示例。我想计算数组的正确索引,因此它不会超出范围。我正在尝试实现单元格1要成为空间第二个是带数据的单元格并重复

 let array = ["0","1","2"] // this is the data with comes for the server so if the count is 3 the cell with data will be 3 and 3 will be just empty cell

 let totalCount = array.count*2

 for i in 0...totalCount {
     if i % 2 == 1{
         //Cell with data is shown here 
         print("Index: \(i-1)") // i'm doing somthing wrong here i need the i to be Index to be "0,1,2"
         print(array[i-1]) // how do i print the data from array at Index 0,1,2
     }else {
         //Space Cell
     }

 }

1 个答案:

答案 0 :(得分:2)

正如我在评论中提到的那样,总会有一点,i-1将比array.count更大。我想你想实现这个目标:

Cell: 0; empty cell
Cell: 0; Index 0
Value: 0
Cell: 2; empty cell
Cell: 2; Index 1
Value: 1
Cell: 4; empty cell
Cell: 4; Index 2
Value: 2
Cell: 6; empty cell

这可以这样实现:

let array = ["0","1","2"]

let totalCount = array.count*2

for i in 0...totalCount {
    if i % 2 == 1{
        //Cell is shown here
        print("Cell: \(i-1); Index \(i/2)")
        print("Value: \(array[i/2])")
    }else {
        //Space Cell
        print("Cell: \(i); empty cell")
    }

}

i-1应该是单元格的索引,而不是数组中的数据。单元格中显示的数据索引应为i/2,以确保此值永远不会大于array.count