5

Right now I have a array that when printed just displays what number I submitted. I would like the word "car" to be in front of every array number. For example: I enter 1 and 2 in the array. When the array is called it would look like [car 1, car 2] not [1,2].

I have added my array variable and what I am calling to print the array:

var arrayOfInt = [Int]()
label.text = String(describing: arrayOfInt)
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85

1 Answers1

12

Try this:

let arrayOfInt: [Int] = [1, 2]
let cars = arrayOfInt.map { "car \($0)" }

as a result, the cars array will be:

["car 1", "car 2"]

finally, convert to string as before:

label.text = String(describing: cars)

The Array.map function returns an array containing the results of mapping the given closure over the array's elements. In other words, it tranforms one array into another one by applying the specified function on each element.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
  • 1
    A slight modification that avoids building the array: let numCars = 11 let cars = Array(1...numCars).map { "car \($0)" } – Norman May 27 '17 at 15:51