0
0
Swiftprogramming~15 mins

FlatMap for nested collections in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
FlatMap for nested collections
📖 Scenario: You work at a bookstore that organizes books by genre. Each genre has a list of book titles. You want to create a single list of all book titles from all genres.
🎯 Goal: Build a Swift program that uses flatMap to combine nested lists of book titles into one flat list.
📋 What You'll Learn
Create a dictionary called booksByGenre with genres as keys and arrays of book titles as values
Create a variable called allBooks that uses flatMap on booksByGenre.values to get a single array of all book titles
Print the allBooks array
💡 Why This Matters
🌍 Real World
Combining nested lists of items is common when working with grouped data, like categories of products or genres of books.
💼 Career
Understanding how to flatten nested collections helps in data processing tasks, making it easier to analyze or display combined information.
Progress0 / 4 steps
1
Create the nested dictionary of books
Create a dictionary called booksByGenre with these exact entries: "Fiction": ["The Alchemist", "1984"], "Science": ["A Brief History of Time", "The Selfish Gene"], and "History": ["Sapiens", "Guns, Germs, and Steel"].
Swift
Need a hint?

Use a Swift dictionary with String keys and array of String values.

2
Prepare to flatten the nested arrays
Create a variable called allBooks and set it to an empty array of strings [] to prepare for collecting all book titles.
Swift
Need a hint?

Declare allBooks as a variable array of strings starting empty.

3
Use flatMap to combine all book lists
Set the variable allBooks to the result of using flatMap on booksByGenre.values to combine all nested arrays into one flat array.
Swift
Need a hint?

Use flatMap on booksByGenre.values with closure { $0 } to flatten.

4
Print the combined list of all books
Write a print statement to display the allBooks array.
Swift
Need a hint?

Use print(allBooks) to show the combined list.