Bird
Raised Fist0
Swiftprogramming~20 mins

Task for launching concurrent work in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Concurrency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift concurrency code?

Consider the following Swift code using Task to run concurrent work. What will be printed?

Swift
import Foundation

func fetchData() async -> String {
    return "Data fetched"
}

Task {
    let result = await fetchData()
    print(result)
}

print("Task launched")
AData fetched\nTask launched
BTask launched
CData fetched
DTask launched\nData fetched
Attempts:
2 left
💡 Hint

Remember that Task runs asynchronously and the main thread continues immediately.

❓ Predict Output
intermediate
2:00remaining
What does this Swift Task code print?

Analyze this Swift code snippet using Task and sleep. What is the output?

Swift
import Foundation

Task {
    print("Start")
    try? await Task.sleep(nanoseconds: 1_000_000_000)
    print("End")
}

print("After Task")
AAfter Task\nStart\nEnd
BStart\nEnd\nAfter Task
CStart\nAfter Task\nEnd
DAfter Task
Attempts:
2 left
💡 Hint

The Task runs asynchronously, so the main thread prints before the task finishes.

🔧 Debug
advanced
2:00remaining
Why does this Swift Task code cause a runtime error?

Examine this Swift code that launches a Task. It crashes at runtime. What is the cause?

Swift
import Foundation

var value = 0

Task {
    value += 1
    print(value)
}

print(value)
AThe variable <code>value</code> is accessed concurrently without synchronization, causing a data race.
BThe variable <code>value</code> is immutable and cannot be changed inside the <code>Task</code>.
CThe <code>Task</code> must be awaited, otherwise it causes a runtime error.
DThe <code>print(value)</code> outside the <code>Task</code> causes a syntax error.
Attempts:
2 left
💡 Hint

Think about shared variable access in concurrent code.

📝 Syntax
advanced
2:00remaining
Which option correctly launches a detached Swift Task?

Choose the correct syntax to launch a detached Task that runs concurrently without inheriting the current context.

A
Task {
    print("Detached task running")
}.detached()
B
Task.detached {
    print("Detached task running")
}
C
Task.runDetached {
    print("Detached task running")
}
D
Task.detach {
    print("Detached task running")
}
Attempts:
2 left
💡 Hint

Look for the official method name to create a detached task.

🚀 Application
expert
3:00remaining
How many concurrent tasks are launched and what is the final output?

Consider this Swift code that launches multiple tasks. How many tasks run concurrently and what is printed?

Swift
import Foundation

for i in 1...3 {
    Task.detached {
        print("Task \(i) started")
        try? await Task.sleep(nanoseconds: 500_000_000)
        print("Task \(i) finished")
    }
}

print("All tasks launched")
A3 tasks run concurrently; output is "All tasks launched" only, because tasks run in background and don't print.
B1 task runs at a time; output is "Task 1 started", "Task 1 finished", then "Task 2 started", etc., ending with "All tasks launched".
C3 tasks run concurrently; output starts with "All tasks launched" followed by each task's start and finish messages in any order.
DNo tasks run because <code>Task.detached</code> is invalid; output is only "All tasks launched".
Attempts:
2 left
💡 Hint

Detached tasks run concurrently and the main thread continues immediately.

Practice

(1/5)
1.

What does Task { } do in Swift concurrency?

easy
A. Creates a synchronous function
B. Starts a new piece of work that runs concurrently with other code
C. Blocks the main thread until the work finishes
D. Stops all other tasks from running

Solution

  1. Step 1: Understand the purpose of Task

    Task { } is used to start work that runs at the same time as other code, without blocking.
  2. Step 2: Compare options

    Only Starts a new piece of work that runs concurrently with other code correctly describes this concurrent behavior. Options A, B, and D are incorrect because they describe blocking, synchronous, or stopping behavior, which Task does not do.
  3. Final Answer:

    Starts a new piece of work that runs concurrently with other code -> Option B
  4. Quick Check:

    Task starts concurrent work = C [OK]
Hint: Task runs code concurrently without blocking [OK]
Common Mistakes:
  • Thinking Task blocks the main thread
  • Confusing Task with synchronous functions
  • Believing Task stops other tasks
2.

Which of the following is the correct syntax to start a new concurrent task in Swift?

?
easy
A. task { fetchData() }
B. async Task { fetchData() }
C. Task.start { fetchData() }
D. Task { await fetchData() }

Solution

  1. Step 1: Recall correct Task syntax

    The correct way to start a concurrent task is Task { } with a closure inside. Using await is needed if calling async functions.
  2. Step 2: Check each option

    Task { await fetchData() } uses correct capitalization and syntax. Options A, C, and D use incorrect keywords or syntax.
  3. Final Answer:

    Task { await fetchData() } -> Option D
  4. Quick Check:

    Correct Task syntax = B [OK]
Hint: Task must be capitalized and use braces { } [OK]
Common Mistakes:
  • Using lowercase 'task' instead of 'Task'
  • Adding 'start' method which doesn't exist
  • Adding 'async' keyword before Task incorrectly
3.

What will be printed by this Swift code?

Task {
    print("Start")
    await Task.sleep(1_000_000_000) // 1 second
    print("End")
}
print("Outside")
medium
A. Start\nOutside\nEnd
B. Outside\nStart\nEnd
C. Outside\nEnd\nStart
D. Start\nEnd\nOutside

Solution

  1. Step 1: Understand Task concurrency

    The Task { } runs concurrently, so "Start" prints immediately when the task begins.
  2. Step 2: Trace print order

    Within the Task, "Start" prints first, then the task sleeps for 1 second, then prints "End". Meanwhile, the main thread continues and prints "Outside" immediately after starting the Task.
  3. Step 3: Determine exact order

    Because the Task closure starts immediately and prints "Start" before sleeping, "Start" prints before "Outside". Then "Outside" prints, and after 1 second delay, "End" prints.
  4. Final Answer:

    Start\nOutside\nEnd -> Option A
  5. Quick Check:

    Task prints Start immediately, main prints Outside, then Task prints End = D [OK]
Hint: Task closure starts immediately and prints Start before main thread prints Outside [OK]
Common Mistakes:
  • Assuming 'Outside' prints before 'Start'
  • Ignoring that Task closure starts immediately
  • Thinking Task blocks main thread
4.

Identify the error in this Swift code that tries to launch a concurrent task:

Task {
    let result = fetchData()
    print(result)
}

Assuming fetchData() is an async function.

medium
A. Missing await before fetchData()
B. Task cannot be used with async functions
C. print cannot be called inside Task
D. fetchData() must be synchronous

Solution

  1. Step 1: Check async function call

    Since fetchData() is async, it must be called with await inside an async context like Task.
  2. Step 2: Identify missing await

    The code misses await before fetchData(), causing a compile error.
  3. Final Answer:

    Missing await before fetchData() -> Option A
  4. Quick Check:

    Async calls need await = A [OK]
Hint: Async calls inside Task need await keyword [OK]
Common Mistakes:
  • Forgetting await on async calls
  • Thinking Task disallows async calls
  • Believing print can't be used inside Task
5.

You want to fetch user data and update the UI without blocking the main thread. Which is the best way to launch this concurrent work?

func updateUI(with data: String) {
    print("UI updated with \(data)")
}

func fetchUserData() async -> String {
    // Simulate network delay
    await Task.sleep(2_000_000_000)
    return "User123"
}

// What code should you write here?
hard
A. Task { let data = fetchUserData() updateUI(with: data) }
B. let data = fetchUserData() updateUI(with: data)
C. Task { let data = await fetchUserData() updateUI(with: data) }
D. updateUI(with: fetchUserData())

Solution

  1. Step 1: Understand async fetch and UI update

    Fetching user data is async and takes time. To avoid blocking, use Task { } to run it concurrently.
  2. Step 2: Use await and update UI inside Task

    Inside the Task, await the async fetch, then update the UI with the result. This keeps UI responsive.
  3. Final Answer:

    Task { let data = await fetchUserData() updateUI(with: data) } -> Option C
  4. Quick Check:

    Await async fetch inside Task, then update UI = A [OK]
Hint: Await async calls inside Task before UI update [OK]
Common Mistakes:
  • Calling async function without await
  • Updating UI outside Task causing blocking
  • Not using Task for concurrency
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