在for-in循环中更改数组的名称

时间:2021-03-06 16:45:01

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.

我想从第一个数组中获取第一个数字,从第二个数组中获取第二个数字,依此类推。我还有一个数字n,它包含有多少个数组和数组。如果有两个数组,它们每个都有两个数字,如果有三个数组,它们每个都有三个数字,等等。

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.

有可能我不知道有多少阵列。

1 个解决方案

#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:

如果您可以创建符合NSKeyValueCoding的类,则可以使用valueForKeyPath(_ :)来获取所需内容。用法示例如下:

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

#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:

如果您可以创建符合NSKeyValueCoding的类,则可以使用valueForKeyPath(_ :)来获取所需内容。用法示例如下:

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