0
0
Swiftprogramming~15 mins

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

Choose your learning style9 modes available
For-in loop with ranges
📖 Scenario: You are helping a small bakery count the number of cupcakes they bake each day for a week. They want to know the total cupcakes baked from Monday to Sunday.
🎯 Goal: Build a Swift program that uses a for-in loop with a range to sum the cupcakes baked each day and print the total.
📋 What You'll Learn
Create a dictionary called cupcakesBaked with keys as days of the week and values as the number of cupcakes baked.
Create a constant days that holds the range from 1 to 7 representing days Monday to Sunday.
Use a for-in loop with the variable day to iterate over days.
Inside the loop, add the cupcakes baked for each day to a variable totalCupcakes.
Print the total cupcakes baked after the loop.
💡 Why This Matters
🌍 Real World
Counting daily production or sales is common in small businesses to track performance and plan inventory.
💼 Career
Using loops and ranges to process data collections is a fundamental skill for software developers, especially in data processing and automation tasks.
Progress0 / 4 steps
1
Create the cupcakes data
Create a dictionary called cupcakesBaked with these exact entries: 1: 12, 2: 15, 3: 10, 4: 20, 5: 18, 6: 25, 7: 22.
Swift
Need a hint?

Use a Swift dictionary with integer keys for days and integer values for cupcakes.

2
Create the days range
Create a constant called days that holds the range from 1 to 7 inclusive.
Swift
Need a hint?

Use the closed range operator ... to include both 1 and 7.

3
Sum cupcakes using a for-in loop
Create a variable called totalCupcakes and set it to 0. Then use a for-in loop with the variable day to iterate over days. Inside the loop, add the cupcakes baked for each day from cupcakesBaked to totalCupcakes. Use optional unwrapping with ?? 0 to handle missing values.
Swift
Need a hint?

Remember to initialize totalCupcakes before the loop and use cupcakesBaked[day] ?? 0 to safely get the value.

4
Print the total cupcakes
Write a print statement to display the text Total cupcakes baked: followed by the value of totalCupcakes using string interpolation.
Swift
Need a hint?

Use print("Total cupcakes baked: \(totalCupcakes)") to show the result.