0
0
Swiftprogramming~30 mins

Map, filter, reduce patterns in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Map, filter, reduce patterns
📖 Scenario: You work at a small fruit store. You have a list of fruit prices and want to do some simple calculations to help with pricing and sales.
🎯 Goal: Learn how to use map, filter, and reduce in Swift to transform, select, and combine data from a list.
📋 What You'll Learn
Create an array of fruit prices
Create a discount rate variable
Use map to apply the discount to all prices
Use filter to find prices above a threshold
Use reduce to calculate the total of filtered prices
Print the final total
💡 Why This Matters
🌍 Real World
Stores and shops often need to update prices, apply discounts, and calculate totals quickly and clearly.
💼 Career
Knowing how to use map, filter, and reduce is useful for data processing tasks in many programming jobs, especially in apps that handle lists of items.
Progress0 / 4 steps
1
Create the fruit prices array
Create an array called fruitPrices with these exact values: 2.5, 3.0, 4.75, 1.25, and 5.0.
Swift
Need a hint?

Use square brackets [] to create an array and separate values with commas.

2
Add a discount rate variable
Create a variable called discountRate and set it to 0.1 to represent a 10% discount.
Swift
Need a hint?

Use let to create a constant variable for the discount rate.

3
Apply discount and filter prices
Use map on fruitPrices to create a new array called discountedPrices where each price is reduced by the discountRate. Then use filter on discountedPrices to create an array called expensivePrices that only contains prices greater than 3.0.
Swift
Need a hint?

Use map with a closure to multiply each price by 1 - discountRate. Use filter with a closure to keep prices greater than 3.0.

4
Calculate total and print
Use reduce on expensivePrices to calculate the total sum and store it in a variable called totalPrice. Then print totalPrice.
Swift
Need a hint?

Use reduce(0) with a closure that adds each price to the sum. Then print the total.