0
0
Swiftprogramming~30 mins

Testing async code in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing async code
📖 Scenario: You are building a simple Swift program that fetches a greeting message asynchronously, simulating a network call.
🎯 Goal: You will write code to test an asynchronous function that returns a greeting string after a short delay.
📋 What You'll Learn
Create an async function that returns a greeting string
Create a variable to hold the expected greeting
Write an async test function that calls the async greeting function
Print the result of the test to verify the greeting matches the expected value
💡 Why This Matters
🌍 Real World
Testing async code is important when working with network calls, file operations, or any tasks that take time to complete in real apps.
💼 Career
Many software jobs require writing and testing asynchronous code to ensure apps work smoothly without freezing or crashing.
Progress0 / 4 steps
1
Create the async greeting function
Create an async function called fetchGreeting() that returns a String. Inside, use try? await Task.sleep(nanoseconds: 1_000_000_000) to wait 1 second, then return the string "Hello, async world!".
Swift
Need a hint?

Use func fetchGreeting() async -> String to define the async function. Use try? await Task.sleep(nanoseconds: 1_000_000_000) to pause for 1 second.

2
Create the expected greeting variable
Create a constant called expectedGreeting and set it to the string "Hello, async world!".
Swift
Need a hint?

Use let expectedGreeting = "Hello, async world!" to create the constant.

3
Write the async test function
Write an async function called testFetchGreeting(). Inside, call fetchGreeting() with await and store the result in a variable called result. Then compare result with expectedGreeting using an if statement. If they match, print "Test passed", else print "Test failed".
Swift
Need a hint?

Define func testFetchGreeting() async. Use let result = await fetchGreeting(). Use if result == expectedGreeting to check and print the test result.

4
Run the test and print the output
Call testFetchGreeting() inside a Task to run the async test. This will print either "Test passed" or "Test failed".
Swift
Need a hint?

Use Task { await testFetchGreeting() } to run the async test and print the result.