[英]Changing the name of an array in a for-in loop
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. 我还有一个数字
n
,其中包含多少个数组和多少个数组。 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. 我可能不知道有多少个数组。
If you can create a class that conforms to NSKeyValueCoding
, you can use valueForKeyPath(_:)
to get what you want. 如果您可以创建符合
NSKeyValueCoding
的类,则可以使用valueForKeyPath(_:)
获得所需的内容。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.