Default parameter values let you give a starting value to a function's input. This way, if you don't provide that input, the function still works smoothly.
When you want a function to work even if some inputs are missing.
When you want to avoid writing many versions of the same function.
When you want to provide common or typical values automatically.
When you want to make your code easier to use and read.
Syntax
Swift
func functionName(parameterName: Type = defaultValue) {
// function body
}
You write the default value after an equals sign = in the parameter list.
If you call the function without that parameter, the default value is used.
Examples
This function says hello. If you don't give a name, it uses "Friend".
func multiply(_ a: Int, by b: Int = 2) -> Int {
return a * b
}
print(multiply(5))
medium
A. Error: Missing argument for parameter 'b'
B. 5
C. 10
D. 25
Solution
Step 1: Understand function parameters
The function multiply takes two parameters: 'a' and 'b' with a default value of 2.
Step 2: Evaluate the call multiply(5)
Only 'a' is provided as 5, so 'b' uses default 2. Result is 5 * 2 = 10.
Final Answer:
10 -> Option C
Quick Check:
5 * default 2 = 10 [OK]
Hint: If argument missing, default value is used [OK]
Common Mistakes:
Expecting error for missing argument
Using first argument for both parameters
Confusing default value with multiplication factor
4. Identify the error in this Swift function declaration:
func greet(name: String = "User", _ age: Int) {
print("Hello \(name), you are \(age) years old.")
}
medium
A. Default parameter must be last in the parameter list
B. Missing return type
C. Cannot use default values with String type
D. Function body syntax error
Solution
Step 1: Check parameter order rules
In Swift, parameters with default values must come after parameters without defaults.
Step 2: Analyze given function
'name' has a default but appears before 'age' which has no default. This causes a compile error.
Final Answer:
Default parameter must be last in the parameter list -> Option A
Quick Check:
Default params last = correct order [OK]
Hint: Place parameters with defaults after others [OK]
Common Mistakes:
Putting default parameters before non-default ones
Assuming return type is mandatory for void functions
Confusing type restrictions on default values
5. You want to write a Swift function formatMessage that takes a text and an optional prefix with default value "Info:". It should return a string combining prefix and text separated by a space. Which is the correct function and call to get output "Info: Hello"?