0
0
Swiftprogramming~5 mins

Global actors (@MainActor) in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a @MainActor in Swift?

@MainActor is a global actor that ensures code runs on the main thread, which is important for updating the user interface safely.

Click to reveal answer
beginner
Why should UI updates be done on the @MainActor?

Because UI frameworks require changes to happen on the main thread to avoid crashes or unexpected behavior.

Click to reveal answer
beginner
How do you mark a Swift function to run on the main actor?

You add @MainActor before the function declaration, like @MainActor func updateUI() { ... }.

Click to reveal answer
intermediate
What happens if you call a @MainActor function from a background thread?

Swift automatically switches execution to the main thread before running the function, ensuring thread safety.

Click to reveal answer
intermediate
Can you mark an entire class as <code>@MainActor</code>? What does it mean?
<p>Yes, marking a class with <code>@MainActor</code> means all its methods and properties run on the main thread.</p>
Click to reveal answer
What does @MainActor guarantee in Swift concurrency?
ACode runs on the main thread
BCode runs on a background thread
CCode runs in parallel on multiple threads
DCode runs only once
How do you declare a function to run on the main actor?
A@MainActor func myFunction() {}
Bfunc mainActor() {}
Cfunc @MainActor myFunction() {}
DmainActor func myFunction() {}
If you call a @MainActor method from a background thread, what happens?
AIt runs immediately on the background thread
BIt causes a crash
CSwift switches to the main thread before running it
DIt runs on a random thread
Which of these can be marked with @MainActor?
AOnly functions
BOnly structs
COnly variables
DFunctions, classes, and properties
Why is it important to use @MainActor for UI code?
ATo improve performance
BTo avoid UI glitches and crashes
CTo run code faster
DTo use less memory
Explain what @MainActor does and why it is important in Swift concurrency.
Think about where UI updates must happen.
You got /3 concepts.
    Describe how you would use @MainActor to protect a class that updates the user interface.
    Consider marking the whole class instead of individual methods.
    You got /3 concepts.