我怎么可能对角3个数组求和?
示例:
[ 6 ,6, 5 ]
[10, 5 ,10]
[ 3 ,20, 1 ]
从左到右,从右到左
6 + 5 +1 = 12
3 + 5 + 5 = 13
这是声明我的数组的方式:
@IBOutlet weak var text1: UITextField!
let text : String = text1.text!
var digits = [Int]()
for element in text.characters
{
digits.append(Int(String(element))!)
}
print(digits)
这就是我的数组以对角线形式求和
let anArray = [[digits],[digits2],[digits3]]
let size = anArray.count
for i in 0..<size {
if anArray[i].count != size {
print("error")
}
}
var diagSum = 0
for i in 0..<size {
for j in 0..<size where i == j {
diagSum += anArray[i][j] // i have an error here Cannot convert value of type '[Int]' to expected argument type 'Int'
}
}
答案 0 :(得分:2)
您可以尝试
let arr1 = [[1,2,3],[1,2,3],[1,2,3]]
var sum = 0
arr1.indices.forEach { sum += arr1[$0][$0] }
arr1.indices.forEach { sum += arr1[$0][arr1.count - 1 - $0] } // not compiled