Bird
Raised Fist0
Swiftprogramming~10 mins

Default parameter values in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Default parameter values
Function call
↓
Check if argument provided?
No→Use default value
Yes↓
Use provided argument
↓
Execute function body with argument
↓
Return result or complete
When calling a function, Swift checks if an argument is given. If not, it uses the default value. Then it runs the function with that value.
Execution Sample
Swift
func greet(name: String = "Friend") {
    print("Hello, \(name)!")
}

greet()
greet(name: "Anna")
This code defines a function with a default name. It prints a greeting using the default or given name.
Execution Table
StepFunction CallArgument Provided?Parameter Value UsedOutput
1greet()No"Friend"Hello, Friend!
2greet(name: "Anna")Yes"Anna"Hello, Anna!
3End--No more calls
💡 No more function calls, execution ends.
Variable Tracker
VariableStartAfter Call 1After Call 2Final
name-"Friend""Anna"-
Key Moments - 2 Insights
Why does greet() print "Hello, Friend!" even though no argument is given?
Because the function has a default value "Friend" for the parameter 'name', it uses this when no argument is provided (see execution_table row 1).
What happens if we provide an argument like greet(name: "Anna")?
The function uses the provided argument "Anna" instead of the default (see execution_table row 2), so it prints "Hello, Anna!".
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the parameter value used when greet() is called without arguments?
A"Friend"
B"Anna"
Cnil
DEmpty string
💡 Hint
Check execution_table row 1 under 'Parameter Value Used'
At which step does the function use the provided argument instead of the default?
AStep 1
BStep 3
CStep 2
DNone
💡 Hint
Look at execution_table row 2 'Argument Provided?' column
If we remove the default value from the function, what will happen when calling greet() without arguments?
AIt will print "Hello, Friend!"
BIt will cause a compile error
CIt will print "Hello, !"
DIt will use nil as the name
💡 Hint
Default values allow calls without arguments; removing it requires argument (see concept_snapshot)
Concept Snapshot
func functionName(parameter: Type = defaultValue) {
  // function body
}

- If argument is missing, defaultValue is used.
- If argument is given, it overrides default.
- Helps avoid writing multiple function versions.
Full Transcript
This visual shows how Swift functions use default parameter values. When you call a function without giving an argument, Swift uses the default value you set. If you provide an argument, it uses that instead. The example greet() prints a greeting using the default name "Friend" if no name is given, or the provided name otherwise. The execution table traces each call, showing the parameter value used and the output. The variable tracker shows how the 'name' parameter changes with each call. Key moments clarify why default values matter and how they work. The quiz tests understanding by asking about parameter values and behavior when defaults are removed.

Practice

(1/5)
1. What is the main purpose of using default parameter values in Swift functions?
easy
A. To make functions run faster
B. To provide fallback values when arguments are not passed
C. To force the caller to always provide arguments
D. To declare variables inside the function

Solution

  1. Step 1: Understand default parameters

    Default parameter values allow a function to use a preset value if no argument is provided.
  2. Step 2: Identify the purpose

    This makes calling the function easier and avoids errors from missing arguments.
  3. Final Answer:

    To provide fallback values when arguments are not passed -> Option B
  4. Quick Check:

    Default parameters = fallback values [OK]
Hint: Default values fill in missing arguments automatically [OK]
Common Mistakes:
  • Thinking default values speed up code
  • Believing default values force arguments
  • Confusing default parameters with variable declarations
2. Which of the following is the correct way to declare a Swift function with a default parameter value?
easy
A. func greet(name: String) { name = "Guest"; print("Hello, \(name)!") }
B. func greet(name: String) = "Guest" { print("Hello, \(name)!") }
C. func greet(name: String default "Guest") { print("Hello, \(name)!") }
D. func greet(name: String = "Guest") { print("Hello, \(name)!") }

Solution

  1. Step 1: Review Swift default parameter syntax

    In Swift, default values are assigned using an equals sign after the parameter type.
  2. Step 2: Check each option

    func greet(name: String = "Guest") { print("Hello, \(name)!") } uses correct syntax: name: String = "Guest". Others have syntax errors.
  3. Final Answer:

    func greet(name: String = "Guest") { print("Hello, \(name)!") } -> Option D
  4. Quick Check:

    Default parameter syntax = type = value [OK]
Hint: Use = after type to set default value [OK]
Common Mistakes:
  • Placing default value outside parentheses
  • Using = after parameter name without type
  • Trying to assign default inside function body
3. What will be the output of this Swift code?
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

  1. Step 1: Understand function parameters

    The function multiply takes two parameters: 'a' and 'b' with a default value of 2.
  2. Step 2: Evaluate the call multiply(5)

    Only 'a' is provided as 5, so 'b' uses default 2. Result is 5 * 2 = 10.
  3. Final Answer:

    10 -> Option C
  4. 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

  1. Step 1: Check parameter order rules

    In Swift, parameters with default values must come after parameters without defaults.
  2. Step 2: Analyze given function

    'name' has a default but appears before 'age' which has no default. This causes a compile error.
  3. Final Answer:

    Default parameter must be last in the parameter list -> Option A
  4. 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"?
hard
A. func formatMessage(text: String, prefix: String = "Info:") -> String { return "\(prefix) \(text)" } print(formatMessage(text: "Hello"))
B. func formatMessage(prefix: String = "Info:", text: String) -> String { return "\(text) \(prefix)" } print(formatMessage(text: "Hello"))
C. func formatMessage(text: String, prefix: String) -> String { return "\(prefix) \(text)" } print(formatMessage(text: "Hello"))
D. func formatMessage(text: String, prefix: String = "Info:") -> String { return "\(text) \(prefix)" } print(formatMessage(text: "Hello"))

Solution

  1. Step 1: Define function with default parameter last

    Parameter with default 'prefix' must come after 'text' without default.
  2. Step 2: Check function call and output

    Calling with only 'text' uses default prefix "Info:" and returns "Info: Hello".
  3. Final Answer:

    func formatMessage(text: String, prefix: String = "Info:") -> String { return "\(prefix) \(text)" } print(formatMessage(text: "Hello")) -> Option A
  4. Quick Check:

    Default param last + call with one arg = correct output [OK]
Hint: Default params last, call with missing arg uses default [OK]
Common Mistakes:
  • Placing default parameter before non-default
  • Calling function without required parameters
  • Swapping order of prefix and text in output
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard