Transforming an array with map

Map

The map function applies a transformation to each element in a array and returns a new array with the modified values.

How does it work?

The basic structure of map looks like this:

let result = myArray.map { item in
    return doSomethingTo(item)
}

Parts of map:

  • { item in ... }: This is a function that takes one parameter:
    • item: The next value in the array.
    • In your function, you decide how to transform each value.

Example: finding the square of numbers

Using a for Loop in Python:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
    squared_numbers.append(number * number)
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Using map in Swift:

let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { number in
    return number * number
}
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]

📝 Task for map

Use map to double every number in an array. Print out the new array.

let numbers = [1, 3, 5, 7, 9]
Reload?