0
0
Swiftprogramming~15 mins

For-in loop with collections in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
For-in Loop with Collections in Swift
📖 Scenario: You work at a small bookstore. You have a list of book titles and their prices. You want to find out which books cost more than $20.
🎯 Goal: Build a Swift program that uses a for-in loop to check each book's price and collect the titles of books costing more than $20.
📋 What You'll Learn
Create a dictionary called books with these exact entries: "Swift Programming": 25, "iOS Development": 18, "Data Structures": 30, "Algorithms": 15
Create a variable called priceThreshold and set it to 20
Use a for-in loop with variables title and price to iterate over books
Inside the loop, check if price is greater than priceThreshold and if so, add title to a list called expensiveBooks
Print the expensiveBooks list at the end
💡 Why This Matters
🌍 Real World
This project shows how to filter items from a collection based on conditions, a common task in apps like shopping, inventory, or data analysis.
💼 Career
Understanding how to loop through collections and apply conditions is essential for software developers working with data structures and user data.
Progress0 / 4 steps
1
Create the books dictionary
Create a dictionary called books with these exact entries: "Swift Programming": 25, "iOS Development": 18, "Data Structures": 30, "Algorithms": 15
Swift
Need a hint?

Use square brackets [] to create a dictionary with key-value pairs separated by colons.

2
Set the price threshold
Create a variable called priceThreshold and set it to 20
Swift
Need a hint?

Use let to create a constant variable with the value 20.

3
Use a for-in loop to find expensive books
Create an empty array called expensiveBooks of type [String]. Then use a for-in loop with variables title and price to iterate over books. Inside the loop, check if price is greater than priceThreshold. If yes, append title to expensiveBooks.
Swift
Need a hint?

Use for (title, price) in books to loop through the dictionary. Use append() to add items to the array.

4
Print the list of expensive books
Write a print statement to display the expensiveBooks array.
Swift
Need a hint?

Use print(expensiveBooks) to show the list of books costing more than $20.