OGeek|极客世界-中国程序员成长平台

标题: ios - 带有检查功能的数组超出范围 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:48
标题: ios - 带有检查功能的数组超出范围

我有一个数组和一个检查函数。

点击按钮时的功能:

// VARS
var workoutArray: [workout]!
var index = Int()

@IBAction func finishExerciseBtnPressed(_ sender: AnyObject) {

    // reload tabledata with next exercise in array

    print("the count of array is \(workoutArray.count)")

    if index <= workoutArray.count {
        index = index + 1
        tableView.reloadData()
        print("The exercise number is \(index)")
    } else {
        // Show finish workout button
        print("No items found anymore")
    }
}

tableView dequeReusableCell的功能:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "workoutStartCell", for: indexPath) as? workoutStartCell {

        let workout = workoutArray[index]
        cell.updateUI(workout: workout, exercise: index + 1)

        return cell

    }else{
        return UITableViewCell()
    }
}

我正在从以前的 viewcontroller 发送数字 0 到这个 vc 顶部的索引 var。我有检查方法 finishExercisePressed 但无论我在做什么,它都会一直计数低谷。它说索引超出范围,但我正在检查索引是否等于或低于数组的计数。

这是我想要达到的目标:

enter image description here

有人可以帮帮我吗?

非常感谢。



Best Answer-推荐答案


I am checking if the index is equal or lower to the count of the arrays.

没错。但是,您是在增加索引之前执行此操作,并且由于索引从零开始,您应该在结束前停止一个索引:

var index = 1 // Set the index to 1 initially to skip the title
...
if index+1 < workoutArray.count {
    index += 1
    tableView.reloadData()
    ...
}

上述检查验证 index 会在 递增后保持在范围内。

关于ios - 带有检查功能的数组超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961590/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4