Kevin Vugts Kevin Vugts - 3 months ago 13
Swift Question

Array out of range with check function

I've got an array and a check function.

Function when tapped on button:

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
print("The exercise number is \(index)")
} else {
// Show finish workout button
print("No items found anymore")

Function of

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

return UITableViewCell()

I am sending from a previous
the number 0 to the index var on the top of this vc. I have the check method
but whatever I am doing it keeps counting trough. It says index out of range but I am checking if the index is equal or lower to the count of the arrays.

This is the thing I would like to achieve:

enter image description here

Can somebody help me out please?

Thanks alot.


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

That's right. However, you are doing it before incrementing the index, and since indexing starts at zero, you should stop one index before the end:

var index = 1 // Set the index to 1 initially to skip the title
if index+1 < workoutArray.count {
    index += 1

The above check verifies that index would stay in range after being incremented.