Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply each Int value in an array by a constant in Swift?

Tags:

arrays

ios

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?

like image 267
Seong Lee Avatar asked May 15 '16 08:05

Seong Lee


1 Answers

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]
like image 110
Ozgur Vatansever Avatar answered Sep 22 '22 15:09

Ozgur Vatansever