Challenge - 5 Problems
MainActor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What happens when you update UI without MainActor?
Consider this Swift async function updating a UILabel text without @MainActor. What is the likely outcome?
iOS Swift
func updateLabel() async { label.text = "Hello" }
Attempts:
2 left
💡 Hint
UI updates must happen on the main thread to avoid problems.
✗ Incorrect
UIKit requires UI changes on the main thread. Without @MainActor, updates may happen on background threads causing crashes or glitches.
📝 Syntax
intermediate2:00remaining
Which function declaration correctly ensures UI updates on the main thread?
Select the correct Swift function declaration that guarantees UI updates run on the main thread using MainActor.
Attempts:
2 left
💡 Hint
The @MainActor attribute goes before the func keyword or before the function name.
✗ Incorrect
The correct syntax is to place @MainActor before the function declaration to ensure it runs on the main thread.
❓ lifecycle
advanced2:00remaining
Why use @MainActor on a ViewModel class for UI updates?
You have a ViewModel class that updates UI-bound properties. Why is marking the entire class with @MainActor beneficial?
Attempts:
2 left
💡 Hint
UI updates must happen on the main thread to avoid crashes.
✗ Incorrect
Marking the ViewModel with @MainActor ensures all its code runs on the main thread, preventing unsafe UI updates from background threads.
🔧 Debug
advanced2:00remaining
Identify the cause of a crash in this async UI update code
This Swift code crashes sometimes. What is the cause?
iOS Swift
func fetchData() async { let data = await loadData() label.text = data } func loadData() async -> String { // Simulate network delay try? await Task.sleep(nanoseconds: 1_000_000_000) return "Loaded" }
Attempts:
2 left
💡 Hint
UI updates must happen on the main thread even after async calls.
✗ Incorrect
After awaiting loadData(), the code continues on a background thread. Updating label.text there causes a crash.
🧠 Conceptual
expert2:00remaining
What does @MainActor guarantee in Swift concurrency?
Choose the best description of what @MainActor guarantees when applied to a function or class.
Attempts:
2 left
💡 Hint
Think about thread safety and UI updates.
✗ Incorrect
@MainActor ensures code runs on the main thread and serializes access to avoid race conditions and unsafe UI updates.