相互添加两个数组的元素

时间:2022-02-01 07:32:19

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实现这一目标的最佳做法是什么?

2 个解决方案

#1


14  

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)

#2


8  

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

首先压缩它们(_:_ :),以产生一个像对数组一样的序列

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:

然后在元组上映射(_ :),并应用+运算符:

let result = zipped.map(+)// result is [5, 7, 24, 29]

All together:

let result = zip(arrayFirst, arraySecond).map(+)

#1


14  

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)

#2


8  

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

首先压缩它们(_:_ :),以产生一个像对数组一样的序列

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:

然后在元组上映射(_ :),并应用+运算符:

let result = zipped.map(+)// result is [5, 7, 24, 29]

All together:

let result = zip(arrayFirst, arraySecond).map(+)