Swift - execution was interrupted by the cause of the multidimensional array exc_bad_access

Learning to write fast code, considering a multidimensional array, you want to iterate over the array, derive the mathematical function stored in the second column, and then add its first column value to 4 separate arrays (not yet created), so in the end I will have 4 arrays containing number from the first column.

However on the line

Function = array3D[index] 

I get an error: fast execution was interrupted due to exc_bad_access

Can anyone help? Code below

 var array3D: [[String]] = [["1", "+"], ["3", "-"], ["5", "x"], ["7", "/"]] var arrayAdd = [""] var arrayMinus = [""] var arrayMultiple = [""] var arrayDivide = [""] var count = array3D.count var countIsZero = false if count != 0 { countIsZero = true } if countIsZero { for index in 0...count { var Function = "" Function = array3D[count][1] println(Function) switch Function { case "+": arrayAdd.append(array3D[count][0]) case "-": arrayMinus.append(array3D[count][0]) case "x": arrayMultiple.append(array3D[count][0]) case "/": arrayDivide.append(array3D[count][0]) default: "" } } } 
+6
source share
3 answers

count will be 4 because the array contains four elements. However, indexing is based on zero, so you should do:

 for index in 0...count-1 

to avoid indexing with number 4 , which will throw an exception.

+4
source

What Klaus said is true. Additionally:

  • You need to make sure that each of your case does not go beyond using count .
  • You have a for index in 0...count statement, but I never see that you are using index , only count . index will be a number that counts from 0.

Good luck
Kyle

+2
source

Function = array3D[4] does not matter <- throw exc_bad_access

Array index 0 to array3D.count - 1

You need to change the for loop to the following: 0..<count (same as 0...count-1 )

 for index in 0..<count { ... } 

Also in your for loop, you use count instead of index :

Below the adjusted cycle:

 for index in 0..<count { var Function = "" Function = array3D[index][1] println(Function) switch Function { case "+": arrayAdd.append(array3D[index ][0]) case "-": arrayMinus.append(array3D[index ][0]) case "x": arrayMultiple.append(array3D[index ][0]) case "/": arrayDivide.append(array3D[index ][0]) default: "" } } 
+1
source

Source: https://habr.com/ru/post/982458/


All Articles