📖 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
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
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
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
Hint
Return total from the function. Call calculateTotal(prices: 10.5, 20.0, 5.25) and print the result.
Practice
(1/5)
1. What does a variadic parameter in Swift allow a function to do?
easy
A. Limit the number of arguments to exactly two
B. Accept any number of values of the same type
C. Accept only one value of any type
D. Return multiple values from a function
Solution
Step 1: Understand variadic parameter purpose
Variadic parameters let a function accept zero or more values of the same type.
Step 2: Compare options with definition
Only Accept any number of values of the same type correctly describes this behavior.
Final Answer:
Accept any number of values of the same type -> Option B
Quick Check:
Variadic parameter = multiple values [OK]
Hint: Variadic means 'variable number' of same type values [OK]
Common Mistakes:
Confusing variadic with multiple return values
Thinking it accepts different types
Assuming it limits arguments
2. Which of the following is the correct way to declare a variadic parameter in Swift?
easy
A. func sum(numbers: Int*) { }
B. func sum(numbers: [Int]) { }
C. func sum(numbers: Int...) { }
D. func sum(numbers: Int) { }
Solution
Step 1: Recall variadic syntax in Swift
Variadic parameters use three dots (...) after the type.
Step 2: Check each option
func sum(numbers: Int...) { } uses 'Int...' which is correct syntax for variadic parameters.
Final Answer:
func sum(numbers: Int...) { } -> Option C
Quick Check:
Variadic syntax = Type... [OK]
Hint: Look for three dots (...) after type for variadic [OK]
Common Mistakes:
Using asterisk (*) instead of three dots
Using array type instead of variadic
Missing dots after type
3. What is the output of this Swift code?
func greet(names: String...) {
for name in names {
print("Hello, \(name)!")
}
}
greet(names: "Anna", "Bob")
medium
A. Hello, Anna!\nHello, Bob!
B. Hello, names!
C. Hello, Anna, Bob!
D. Error: Cannot use variadic parameter here
Solution
Step 1: Understand variadic parameter behavior
The parameter 'names' collects all arguments into an array of strings.
Step 2: Trace the for loop output
The loop prints "Hello, Anna!" and then "Hello, Bob!" each on a new line.
Final Answer:
Hello, Anna!\nHello, Bob! -> Option A
Quick Check:
Variadic parameter prints each argument separately [OK]
Hint: Variadic acts like array; loop prints each item [OK]
Common Mistakes:
Thinking it prints all names in one line
Assuming a syntax error
Confusing parameter name with output
4. Identify the error in this Swift function using variadic parameters:
func multiply(numbers: Int...) -> Int {
var result = 1
for i in 0..
medium
A. The for loop syntax is incorrect
B. Missing return statement in function
C. Variadic parameters cannot be used with Int type
D. Calling multiply without any arguments causes an error
Solution
Step 1: Analyze function call
The call 'multiply(numbers: )' passes no arguments, which is allowed but syntax requires no empty parentheses.
Step 2: Understand Swift call syntax for variadic
Calling with empty parentheses after variadic parameter name is invalid; omit arguments or provide values.
Final Answer:
Calling multiply without any arguments causes an error -> Option D
Quick Check:
Empty variadic call syntax invalid [OK]
Hint: Call variadic with values or omit parentheses if none [OK]
Common Mistakes:
Thinking for loop is wrong
Believing Int can't be variadic
Missing return statement error
5. How can you write a Swift function that accepts any number of integers and returns their average as a Double using variadic parameters?
func average(numbers: Int...) -> Double { Double(numbers.reduce(0, +)) / Double(numbers.count) } correctly uses 'Int...' to accept any number of integers.
Step 2: Calculate average as Double
It sums all numbers and divides by count, converting to Double for decimal average.