1

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.

4
  • 5
    Create an array of your arrays let arr = [arr1, arr2, arr3] then you can do firstDiag += Int(arr[i][i])! Commented Jan 1, 2016 at 16:22
  • @vacawama, that did it! Commented Jan 1, 2016 at 16:36
  • 1
    @vacawama you should post it as answer so you can get credits ;-) Commented Jan 4, 2016 at 13:52
  • @vacawama, I did edit my post with a little more information at the bottom. Commented Jan 4, 2016 at 13:53

1 Answer 1

1

If you can create a class that conforms to NSKeyValueCoding, you can use valueForKeyPath(_:) to get what you want. Example of the usage would be:

import Foundation
class Test: NSObject {

    let array0 = [1, 2, 3]
    let array1 = [4, 5, 6]
    let array2 = [7, 8, 9]
    let n = 3

    func calculate() -> Int {
        var firstDiag = 0
        for i in 0..<n {
            if let array = valueForKeyPath("array\(i)") as? Array<Int> {
                firstDiag += array[i]
            }
        }

        return firstDiag
    }
}

let a = Test()
a.calculate() // Prints 15
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.