简体   繁体   English

将两个数组的元素相加

[英]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.

相关问题 如何在彼此不相邻的两个元素之间添加拖尾/前导约束 - How to add tailing/leading constraint between two elements which aren't next to each other 如何使用约束添加两个视图 - How to add two views on each other with constraints Swift-在tableView中将两个数组元素添加到detailTextLabel - Swift - Add two array elements to detailTextLabel in tableView 在 Swift 中相互检查数组中的所有元素 - Checking all elements in an array in Swift against each other 在数组中查找具有相同颜色的元素,如果元素彼此相邻,则显示true - Find elements in array with the same color and print true if they are next to each other 每次调用特定函数时向数组添加元素 - Add elements to array each time a particular function is called 如何在Swift中将两个元素(不知道其宽度)彼此居中? - how can I center two elements (without knowing their width) next to each other in Swift? 如何在TableView的每一行中添加按钮,图像和其他UI元素? (iOS,快速) - How to add buttons, images and other UI elements in each row of TableView? (iOS,Swift) 两个PFObject可以互相指向吗? - Can two PFObjects point at each other? 如何使两个子视图相互交互? - How to have two subviews interact with each other?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM