I have a set number of arrays that I need to loop through. There is only one difference in their names, and that is a number at the end of it.
arr1
arr2
arr3
I want to get the first number from the first array, the second number from the second array and so on. I also have a number n that contains the number of how many arrays and number of arrays there are. If there are two arrays, they each have two numbers, if there are three arrays they each have three numbers, etc.
Originally I was looping through it like this:
var firstDiag = 0
for (var i = 0; i < n; i++) {
if (i == 0) {
firstDiag += Int(arr1[i])!
} else if (i == 1) {
firstDiag += Int(arr2[i])!
} else if (i == 2) {
firstDiag += Int(arr3[i])!
} else {
firstDiag += 0
}
}
But I was wondering if I could somehow do it this way
for i in 0...n {
firstDiag += Int(arr<i>[i])!
}
Where I change the last number on the array name. Is it possible to do this, or is there something else I should be doing?
There is the possibility I don't know how many arrays there are.
let arr = [arr1, arr2, arr3]then you can dofirstDiag += Int(arr[i][i])!