gpt4 book ai didi

arrays - 如何计算数组的正确索引

转载 作者:行者123 更新时间:2023-11-28 12:28:49 26 4
gpt4 key购买 nike

我已经实现了一个 tableView,它的工作方式类似于下面的示例。我想为数组计算正确的索引,这样它就不会超出范围。我正在努力实现单元格 1 成为空间 2nd 成为具有数据的单元格并重复

 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
}

}

最佳答案

正如我在评论中提到的,总会有一个点,其中 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

关于arrays - 如何计算数组的正确索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42673921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com