0
0
Swiftprogramming~5 mins

MainActor for UI work in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @MainActor attribute in Swift?
The @MainActor attribute ensures that the annotated code runs on the main thread, which is important for updating the user interface safely and avoiding concurrency issues.
Click to reveal answer
beginner
How does @MainActor help with UI updates in Swift concurrency?
It guarantees that UI updates happen on the main thread, preventing crashes or unexpected behavior caused by updating UI elements from background threads.
Click to reveal answer
beginner
What happens if you try to update UI elements from a background thread without using @MainActor?
Updating UI from a background thread can cause crashes or visual glitches because UI frameworks expect changes on the main thread only.
Click to reveal answer
beginner
How do you mark a Swift function to run on the main thread using concurrency features?
You add the @MainActor attribute before the function declaration to ensure it runs on the main thread.
Click to reveal answer
intermediate
Explain the difference between @MainActor and manually dispatching to the main queue.
@MainActor is a language-level feature that automatically manages execution on the main thread, making code cleaner and safer, while manually dispatching uses DispatchQueue.main.async and requires explicit calls.
Click to reveal answer
What does the @MainActor attribute guarantee in Swift concurrency?
ACode runs only once
BCode runs on the main thread
CCode runs in parallel on multiple threads
DCode runs on a background thread
Why should UI updates be done on the main thread?
ATo avoid UI crashes and glitches
BTo speed up the app
CTo use less memory
DTo run code in parallel
Which Swift attribute helps you run a function on the main thread automatically?
A@MainActor
B@BackgroundActor
C@UIThread
D@AsyncMain
What is a common alternative to @MainActor for running code on the main thread?
AOperationQueue.background
BDispatchQueue.global.async
CThread.sleep()
DDispatchQueue.main.async
If a function is marked with @MainActor, what happens when you call it from a background thread?
AThe app crashes immediately
BThe function runs on the background thread anyway
CThe call is automatically switched to the main thread
DThe function runs twice
Describe why @MainActor is important for UI work in Swift concurrency.
Think about how UI updates must happen safely.
You got /4 concepts.
    Explain how @MainActor compares to using DispatchQueue.main.async for UI updates.
    Consider ease of use and safety.
    You got /4 concepts.