📖 Scenario: Imagine you are organizing a small event and want to print messages for each guest using a function that accepts a closure to customize the greeting.
🎯 Goal: You will create a function that takes a closure to print a greeting message. Then, you will call this function using trailing closure syntax to make your code cleaner and easier to read.
📋 What You'll Learn
Create a function called greetGuest that takes a closure parameter named message with no parameters and no return value.
Create a variable called guestName with the value "Alex".
Call the greetGuest function using trailing closure syntax to print a greeting message that includes the guestName.
Print the greeting message inside the closure.
💡 Why This Matters
🌍 Real World
Trailing closure syntax is often used in Swift when working with asynchronous tasks, animations, or event handlers to write cleaner and more readable code.
💼 Career
Understanding trailing closures helps you read and write Swift code more effectively, which is important for iOS app development and working with Swift frameworks.
Progress0 / 4 steps
1
Create the guest name variable
Create a variable called guestName and set it to the string "Alex".
Swift
Hint
Use var guestName = "Alex" to create the variable.
2
Create the greetGuest function
Create a function called greetGuest that takes one parameter named message. This parameter is a closure with no parameters and no return value. The function should call the message closure inside its body.
Swift
Hint
Define the function with func greetGuest(message: () -> Void) and call message() inside.
3
Call greetGuest using trailing closure syntax
Call the greetGuest function using trailing closure syntax. Inside the closure, print the message "Hello, \(guestName)! Welcome to the event.".
Swift
Hint
Use greetGuest { print("Hello, \(guestName)! Welcome to the event.") } to call the function.
4
Print the greeting message
Run the program to print the greeting message using the trailing closure syntax call to greetGuest.
Swift
Hint
Just run the program. The message should print automatically.
Practice
(1/5)
1. What does trailing closure syntax allow you to do in Swift? func perform(action: () -> Void) { action() }
easy
A. Write the last closure argument outside the parentheses
B. Use closures only inside parentheses
C. Avoid using closures altogether
D. Write closures only as named functions
Solution
Step 1: Understand closure arguments in Swift functions
Swift functions can take closures as arguments, usually inside parentheses.
Step 2: Identify trailing closure syntax purpose
Trailing closure syntax lets you write the last closure argument outside the parentheses for cleaner code.
Final Answer:
Write the last closure argument outside the parentheses -> Option A
Quick Check:
Trailing closure syntax = last closure outside parentheses [OK]
Hint: Last closure can go outside parentheses for clarity [OK]
Common Mistakes:
Thinking closures must always be inside parentheses