问题
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