Seong Lee Seong Lee - 6 months ago 28
Swift Question

How to multiply Int Array values in Swift?

Say, I have an array

[20, 2, 3]


How can I multiply each Int value of this array in Swift?

So 2 x array becomes
[40, 4, 6]
, 3 x array becomes
[60, 6, 9]
and so on?

Answer

You can use .map():

let values = [20, 2, 3]
let doubles = values.map { $0 * 2 }
let triples = values.map { $0 * 3 }

If you want to update the array in-place:

var values = [20, 2, 3]

values.enumerate().forEach { index, value in
  values[index] = value * 2
}
// values is now [40, 4, 6]