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?
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.enumerated().forEach { index, value in
values[index] = value * 2
}
// values is now [40, 4, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With