Seong Lee Seong Lee -3 years ago 123
iOS Question

How to multiply each Int value in an array by a constant 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 Source

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 do the update in-place:

var values = [20, 2, 3]

values.enumerate().forEach { index, value in
  values[index] = value * 2
}
// values is now [40, 4, 6]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download