乘以数组位置 Swift

Multiply Array position Swift

我需要用 Swift 语言修复此代码。我不知道如何将数组位置 mut1 和 mut2 值相乘。结果是 8.

var mut1 = [7,-4,5]
var mut2 = [3,2,-1]

var multiply = mut1[0] * mut2[0] + mut1[1] * mut2[1] + mut1[2] * mut2[2]

print(multiply)

使用“For”循环计算相同数组位置的和

var mut1 = [7,-4,5]
var mut2 = [3,2,-1]
var productsum = 0
 for i in 0..<mut1.count {
        let product = mut1[i] * mut2[i]
        productsum += product
    }
    print(productsum)

如果你想要 Swift-like 解决方案,你可以试试这个:

var mut1 = [7,-4,5]
var mut2 = [3,2,-1]

var multiply = zip(mut1, mut2).map { [=10=] *  }.reduce(0, +)

print(multiply) // 8