0
0
Swiftprogramming~15 mins

Default parameter values in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Parameter Values in Swift Functions
📖 Scenario: You are creating a simple greeting app that can say hello to users. Sometimes, users provide their name, and sometimes they don't. You want the app to greet users properly in both cases.
🎯 Goal: Build a Swift function that uses default parameter values to greet users by name or with a generic greeting if no name is given.
📋 What You'll Learn
Create a function called greet that takes one parameter name of type String.
Set a default value for the name parameter to "Guest".
Call the greet function twice: once without any argument and once with the argument "Alice".
Print the greeting message inside the greet function.
💡 Why This Matters
🌍 Real World
Default parameter values are useful in apps where some inputs are optional, like greeting users who may or may not provide their names.
💼 Career
Understanding default parameters helps you write cleaner, more flexible functions, a skill important for Swift developers building user-friendly apps.
Progress0 / 4 steps
1
Create the greet function with a name parameter
Write a Swift function called greet that takes one parameter named name of type String. Inside the function, print the message "Hello, \(name)!".
Swift
Need a hint?

Define a function with func, add a parameter name: String, and use print with string interpolation.

2
Add a default value to the name parameter
Modify the greet function so that the name parameter has a default value of "Guest".
Swift
Need a hint?

Add = "Guest" after the parameter type to set a default value.

3
Call greet without an argument
Call the greet function without passing any argument.
Swift
Need a hint?

Just write greet() to call the function with the default parameter.

4
Call greet with the argument "Alice" and print both greetings
Call the greet function with the argument "Alice" after the call without arguments. The program should print both greetings.
Swift
Need a hint?

Call greet("Alice") after greet() to see both greetings.