"Zipping" the two arrays gives a sequence of tuples (a_i, b_i)
which can then be multiplied element-wise:
let A = [1,2,3,4]
let B = [2,3,4,5]
let C = zip(A, B).map { $0 * $1 }
print(C) // [2, 6, 12, 20]
(If the arrays have different length then zip
silently ignores the extra elements of the longer array.)
As @appzYourLife correctly said, you can also pass the multiplication
operator directly as an argument to map
instead of a closure expression:
let C = zip(A, B).map(*)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…