Challenge - 5 Problems
MainActor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using @MainActor?
Consider this Swift code snippet using @MainActor to update UI state. What will be printed?
Swift
import Foundation @MainActor class ViewModel { var count = 0 func increment() { count += 1 print("Count is now \(count)") } } let vm = ViewModel() Task { await vm.increment() }
Attempts:
2 left
💡 Hint
Remember @MainActor ensures code runs on the main thread for UI safety.
✗ Incorrect
The @MainActor attribute on ViewModel means all its methods run on the main thread. Calling await vm.increment() inside Task correctly switches to main thread, so count increments and prints 1.
🧠 Conceptual
intermediate1:30remaining
Why use @MainActor for UI updates in Swift?
Which of these best explains why @MainActor is used for UI work in Swift concurrency?
Attempts:
2 left
💡 Hint
Think about thread safety and UI frameworks.
✗ Incorrect
UI frameworks require updates on the main thread. @MainActor ensures code runs there, preventing crashes from concurrent access.
🔧 Debug
advanced2:00remaining
What error occurs with this code missing @MainActor?
This Swift code updates UI state without @MainActor. What error will it cause?
Swift
class ViewModel { var text = "" func updateText() { text = "Hello" print(text) } } let vm = ViewModel() Task { vm.updateText() }
Attempts:
2 left
💡 Hint
UI updates must happen on the main thread.
✗ Incorrect
Without @MainActor, updateText runs on a background thread inside Task, causing runtime warnings or crashes due to UI updates off main thread.
📝 Syntax
advanced1:30remaining
Which option correctly applies @MainActor to a Swift function?
Choose the correct syntax to mark a Swift function to run on the main actor.
Attempts:
2 left
💡 Hint
Attributes come before the function keyword.
✗ Incorrect
The correct syntax places @MainActor before the function declaration. Other options are invalid syntax.
🚀 Application
expert2:30remaining
How many times is the UI updated in this Swift code?
Given this Swift code using @MainActor and async calls, how many times will the UI update print statement run?
Swift
import Foundation @MainActor class UIHandler { var updates = 0 func updateUI() { updates += 1 print("UI updated \(updates) times") } } let handler = UIHandler() Task { await handler.updateUI() Task { await handler.updateUI() } await handler.updateUI() }
Attempts:
2 left
💡 Hint
Count each awaited call to updateUI inside the tasks.
✗ Incorrect
There are three awaited calls to updateUI: one in the outer Task, one nested Task, and one more in the outer Task. Each increments and prints once.