0

For example say I have the array:

let nums = [1, 2, 3, 4, 5, 6]

I would like to output a new array with the cube values: [1, 8, 27, 64, 125, 216]

Do I have to use a loop?

  • 1
    `nums.map { $0 * $0 * $0 }` – Leo Dabus Sep 03 '18 at 21:47
  • Possible duplicate of [How to multiply each Int value in an array by a constant in Swift?](https://stackoverflow.com/questions/37236312/how-to-multiply-each-int-value-in-an-array-by-a-constant-in-swift) and [Exponentiation operator in Swift](https://stackoverflow.com/questions/24065801/exponentiation-operator-in-swift) – rmaddy Sep 03 '18 at 21:56

1 Answers1

1

You can use map() and pow() together:

import Foundation

let nums = [1, 2, 3, 4, 5, 6]
let cubes = nums.map { Int(pow(Double($0), 3)) }
let raisedBySix = nums.map { Int(pow(Double($0), 6)) }
print(cubes)       // [1, 8, 27, 64, 125, 216]
print(raisedBySix) // [1, 64, 729, 4096, 15625, 46656]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40