0
0
Swiftprogramming~30 mins

Escaping closures (@escaping) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @escaping Closures in Swift
📖 Scenario: Imagine you are building a simple app that fetches user data asynchronously. You want to practice how to use @escaping closures in Swift to handle the data after the fetch completes.
🎯 Goal: Build a Swift program that defines a function with an @escaping closure parameter, simulates an asynchronous fetch, and then calls the closure with the fetched data.
📋 What You'll Learn
Create a function called fetchUserData that takes an @escaping closure parameter named completion.
The completion closure should accept a String parameter representing user data.
Inside fetchUserData, simulate a delay using DispatchQueue.main.asyncAfter to mimic asynchronous fetching.
Call the completion closure inside the async block with the string "User data loaded".
Call fetchUserData and print the result inside the closure.
💡 Why This Matters
🌍 Real World
Escaping closures are used in real apps to handle asynchronous tasks like network requests, animations, or user interactions that complete later.
💼 Career
Understanding @escaping closures is essential for Swift developers working on iOS apps that fetch data from servers or perform delayed actions.
Progress0 / 4 steps
1
Create the fetchUserData function with an @escaping closure parameter
Write a function called fetchUserData that takes one parameter named completion. This parameter should be a closure marked with @escaping that accepts a String and returns Void. Inside the function, leave the body empty for now.
Swift
Need a hint?

Remember to mark the closure parameter with @escaping because it will be called after the function returns.

2
Add asynchronous simulation inside fetchUserData
Inside the fetchUserData function, use DispatchQueue.main.asyncAfter with a delay of 1 second to simulate asynchronous work. Inside the async block, call the completion closure with the string "User data loaded".
Swift
Need a hint?

Use DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) to delay the closure call by 1 second.

3
Call fetchUserData and handle the result
After the fetchUserData function, write a call to fetchUserData passing a closure that takes one parameter named data of type String. Inside the closure, print the data.
Swift
Need a hint?

Call fetchUserData and provide a closure that prints the received data.

4
Run the program and see the output
Run the program to see the printed output from the closure after the simulated delay.
Swift
Need a hint?

Wait one second after running to see the output printed.