Bird
0
0

You have this Swift function:

medium📝 Debug Q14 of 15
iOS Swift - Concurrency
You have this Swift function:
func updateLabel() {
  label.text = "Hello"
}
When called from a background thread, the app crashes. How can you fix it using MainActor?
AAdd <code>@MainActor</code> before the function declaration
BCall <code>updateLabel()</code> inside <code>DispatchQueue.global()</code>
CRemove the function and update label directly
DWrap label update inside <code>DispatchQueue.main.async</code> without @MainActor
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of crash

    UI updates must happen on main thread; background thread causes crash.
  2. Step 2: Use @MainActor to fix

    Adding @MainActor before function ensures it runs on main thread, preventing crash.
  3. Final Answer:

    Add @MainActor before the function declaration -> Option A
  4. Quick Check:

    @MainActor fixes UI thread crash [OK]
Quick Trick: Use @MainActor to run UI code on main thread automatically [OK]
Common Mistakes:
  • Using global queue instead of main queue
  • Updating UI directly from background thread
  • Ignoring thread safety causing crashes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes