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: ""
}
}
}
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.
What Klaus said is correct. Additionally:
case statements doesn't go out of bounds by using count. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With