0
0
Swiftprogramming~30 mins

Variadic parameters in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Variadic Parameters in Swift
📖 Scenario: You are creating a simple Swift program to calculate the total price of items bought in a store. The number of items can vary each time.
🎯 Goal: Build a Swift function that uses variadic parameters to accept any number of item prices and calculate their total.
📋 What You'll Learn
Create a function named calculateTotal that takes a variadic parameter of type Double named prices.
Inside the function, calculate the sum of all prices.
Return the total sum as a Double.
Call the function with multiple price values and print the result.
💡 Why This Matters
🌍 Real World
Variadic parameters let you write flexible functions that can handle any number of inputs, like calculating totals for shopping carts or processing multiple user inputs.
💼 Career
Understanding variadic parameters is useful for writing clean, reusable code in Swift apps, especially when dealing with lists of data where the count can change.
Progress0 / 4 steps
1
Create the function with variadic parameter
Write a Swift function named calculateTotal that takes a variadic parameter called prices of type Double. The function should return a Double. Do not add any code inside the function yet.
Swift
Need a hint?

Use Double... to declare a variadic parameter named prices.

2
Add a variable to hold the total sum
Inside the calculateTotal function, create a variable named total and set it to 0.0 to hold the sum of prices.
Swift
Need a hint?

Declare total as a Double variable initialized to 0.0.

3
Sum all prices using a for loop
Use a for loop with variable price to iterate over prices inside the calculateTotal function. Add each price to the total variable.
Swift
Need a hint?

Use for price in prices to loop through all prices and add each to total.

4
Return the total and print the result
Change the return statement to return the total variable. Then, call calculateTotal with the prices 10.5, 20.0, and 5.25. Print the result using print.
Swift
Need a hint?

Return total from the function. Call calculateTotal(prices: 10.5, 20.0, 5.25) and print the result.