Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - execution was interrupted reason exc_bad_access multidimensional array

Learning to write swift code, looking at a multidimensional array, want to iterate through the array, withdraw the math function stored in the second column, and then add its first column value to 4 separate arrays (yet to be created) so at the end I will have 4 arrays, containing the number from the first column.

However on line

 Function = array3D[index]

I am getting error: swift execution was interrupted reason 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: ""
       }
    }  
}
like image 797
James Walker Avatar asked Feb 13 '15 19:02

James Walker


2 Answers

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

for index in 0...count-1

to avoid indexing with the number 4 which would cause the exception.

like image 171
Klaus Byskov Pedersen Avatar answered Oct 21 '22 23:10

Klaus Byskov Pedersen


What Klaus said is correct. Additionally:

  • You'll want to ensure that each of your case statements doesn't go out of bounds by using count.
  • You have the for index in 0...countstatement, but I never see you using index, only count. index will be the number that counts up from 0.

Good luck,
Kyle

like image 22
kbpontius Avatar answered Oct 22 '22 01:10

kbpontius