我有2个类型Int的数组,如此
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
我想添加每个数组的元素,比如arrayFirst [0] + arraySecond [0],arrayFirst [1] + arraySecond [1]等等,并将它分配给另一个数组,所以数组的结果会就像
[5,7,24,29]
使用swift3
答案 0 :(得分:16)
您可以像这样添加两个数组
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
let result = zip(arrayFirst, arraySecond).map(+)
print(result)
答案 1 :(得分:9)
let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]
首先zip(_:_:)
它们,以产生一个像对数组一样的序列
let zipped = zip(arrayFirst, arraySecond)
// zipped acts like [(1, 4), (2, 5), (7, 17), (9, 20)]
然后在元组上map(_:)
,并应用+
运算符:
let result = zipped.map(+)
// result is [5, 7, 24, 29]
所有在一起:
let result = zip(arrayFirst, arraySecond).map(+)