Ad space (banner)
๐ŸฆSwift Lessons
Lesson 23 / 68

Transforming an Array (map)

In this lesson you will learn how to transform an array with map in Swift, so you can process every element in one go. This is for anyone searching for "Swift map how to use".

.map { } applies the same operation to every element and produces a new array. Think of it as a machine on a conveyor belt that processes every product that passes through it in the same way.

The sample code builds a new array doubled with every element of the original [1, 2, 3] doubled, using nums.map { $0 * 2 }. The $0 shorthand refers to the closure's first argument - a distinctly Swift notation.

A common stumbling block for beginners is that map returns a new array rather than changing the original. Compared with writing a for loop element by element, what you are trying to do shows up directly in the code.

In real-world development there is also compactMap, a handy relative that removes nils while transforming - a technique you will meet constantly.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)