通过对另外两个数组的所有元素应用二元运算,在 Swift 中创建一个数组
Creating an array in Swift by applying binary operation to all elements of two other arrays
在Swift中是否有一种通过对其他两个数组的元素应用二元运算来创建数组的简洁方法?
例如:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[[=11=]]+b[[=11=]]} // c = [5, 7, 9]
如果你用zip组合元素,你可以参考+
只用+
:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = zip(a, b).map(+) // [5, 7, 9]
更新:
您可以这样使用 indices
:
for index in a.indices{
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]
(感谢 Alexander 的评论,这更好,因为我们不必处理 element
本身,我们只处理 index
)
旧答案:
你可以枚举得到索引:
var sum = [Int]()
for (index, _) in a.enumerated(){
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]
在Swift中是否有一种通过对其他两个数组的元素应用二元运算来创建数组的简洁方法?
例如:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[[=11=]]+b[[=11=]]} // c = [5, 7, 9]
如果你用zip组合元素,你可以参考+
只用+
:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = zip(a, b).map(+) // [5, 7, 9]
更新:
您可以这样使用 indices
:
for index in a.indices{
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]
(感谢 Alexander 的评论,这更好,因为我们不必处理 element
本身,我们只处理 index
)
旧答案:
你可以枚举得到索引:
var sum = [Int]()
for (index, _) in a.enumerated(){
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]