[英]Add elements of two array with each other
I have 2 Array of type Int like this我有 2 个像这样 Int 类型的数组
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
I want to add the elements of each array, like arrayFirst[0] + arraySecond[0], arrayFirst[1] + arraySecond[1] an so on and assign it to another array, so the result of the array would be like我想添加每个数组的元素,如 arrayFirst[0] + arraySecond[0]、arrayFirst[1] + arraySecond[1] 等等并将其分配给另一个数组,所以数组的结果会像
[5, 7, 24, 29] [5, 7, 24, 29]
What would be the best practice to achieve this using swift3
使用swift3
实现这一目标的最佳实践是swift3
You can add both the arrays like this您可以像这样添加两个数组
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
let result = zip(arrayFirst, arraySecond).map(+)
print(result)
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
First zip(_:_:)
them, to produce a sequence that acts like array of pairs首先zip(_:_:)
它们,以产生一个像数组对一样的序列
let zipped = zip(arrayFirst, arraySecond)
// zipped acts like [(1, 4), (2, 5), (7, 17), (9, 20)]
Then map(_:)
over the tuples, and apply the +
operator:然后map(_:)
在元组上,并应用+
运算符:
let result = zipped.map(+)
// result is [5, 7, 24, 29]
All together:全部一起:
let result = zip(arrayFirst, arraySecond).map(+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.