相互添加两个数组的元素
我有2个这样的Inttypes的数组
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
来实现这个最好的做法是什么swift3
你可以像这样添加这两个数组
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]
先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(+)