0
0
iOS Swiftmobile~5 mins

MainActor for UI updates in iOS Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the MainActor in Swift concurrency?
The MainActor ensures that code runs on the main thread, which is necessary for updating the user interface safely and avoiding crashes.
Click to reveal answer
beginner
How do you mark a Swift function to run on the main thread using MainActor?
You add the attribute @MainActor before the function declaration to ensure it runs on the main thread.
Click to reveal answer
beginner
Why should UI updates be performed on the main thread in iOS apps?
Because UIKit is not thread-safe, updating UI elements on any thread other than the main thread can cause unpredictable behavior or crashes.
Click to reveal answer
intermediate
What happens if you try to update UI from a background thread without using MainActor?
The app may crash or behave unexpectedly because UI updates must happen on the main thread to be safe.
Click to reveal answer
intermediate
How does using @MainActor improve code readability and safety?
It clearly shows which parts of the code run on the main thread, making it easier to avoid threading bugs and maintain UI update safety.
Click to reveal answer
What does the @MainActor attribute do in Swift?
ARuns the code on the main thread
BRuns the code on a background thread
CDisables concurrency
DRuns the code asynchronously on any thread
Why must UI updates happen on the main thread in iOS apps?
ABecause the main thread is faster
BBecause UI updates are asynchronous
CBecause background threads are disabled
DBecause UIKit is not thread-safe
Which of these is a correct way to mark a function to run on the main thread?
A@MainActor func updateUI() { }
Bfunc updateUI() @MainActor { }
Cfunc @MainActor updateUI() { }
Dfunc updateUI() { @MainActor }
What might happen if you update UI from a background thread without MainActor?
AThe UI updates instantly
BNothing happens
CThe app may crash or behave unpredictably
DThe update is queued automatically
How does MainActor help with concurrency in Swift?
AIt forces all code to run sequentially
BIt ensures UI code runs on the main thread safely
CIt disables concurrency
DIt runs code on multiple threads simultaneously
Explain why using @MainActor is important for UI updates in iOS apps.
Think about what happens if UI updates run on the wrong thread.
You got /4 concepts.
    Describe how you would mark a Swift function to ensure it runs on the main thread using MainActor.
    Focus on the syntax to annotate the function.
    You got /3 concepts.