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

Flattening an Array

In this lesson you will learn how to flatten a nested array in Swift and how the handy flatMap method works. This is for anyone searching for "Swift flatMap how to use".

Expanding an array that contains other arrays into one flat array is called flattening. In Swift you use .flatMap { $0 }.

The sample code expands the nested [[1, 2], [3, 4], [5]] into the single array [1, 2, 3, 4, 5] with nested.flatMap { $0 }. As the name suggests, flatMap combines map and flatten in one convenient method.

A common stumbling block for beginners is the difference between map and flatMap. With map alone the arrays remain nested; flatMap is what removes one level.

In real-world development it is a useful technique whenever you want to treat nested data as one list.

๐Ÿ“– 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)