Creating an array in Swift by applying binary operation to all elements of two other arrays

谁说胖子不能爱 提交于 2019-12-19 11:19:18

问题


Is there a concise way in Swift of creating an array by applying a binary operation on the elements of two other arrays?

For example:

let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[$0]+b[$0]} // c = [5, 7, 9]

回答1:


If you use zip to combine the elements, you can refer to + with just +:

let a = [1, 2, 3]
let b = [4, 5, 6]    
let c = zip(a, b).map(+)  // [5, 7, 9]



回答2:


Update:

You can use indices like this:

for index in a.indices{
    sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]

(Thanks to Alexander's comment this is better, because we don't have to deal with the element itself and we just deal with the index)

Old answer:

you can enumerate to get the index:

var sum = [Int]()
for (index, _) in a.enumerated(){
    sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]


来源:https://stackoverflow.com/questions/41209578/creating-an-array-in-swift-by-applying-binary-operation-to-all-elements-of-two-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!