Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to mark the function to run on the main thread.
Swift
@[1] func updateUI() { print("UI updated") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong actor attribute that does not guarantee main thread execution.
✗ Incorrect
The @MainActor attribute ensures the function runs on the main thread, which is required for UI updates.
2fill in blank
mediumComplete the code to ensure the async function runs on the main thread.
Swift
func fetchData() async {
await [1] {
print("Data fetched and UI updated")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using DispatchQueue.global() which runs on a background thread.
Using Task.detached which runs detached from any actor.
✗ Incorrect
MainActor.run ensures the closure runs on the main thread asynchronously.
3fill in blank
hardFix the error in the code to update the UI safely on the main thread.
Swift
class ViewModel { func update() async { await [1] { print("UI updated") } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using DispatchQueue.global() which runs on a background thread.
Using Task.detached which runs detached from any actor.
✗ Incorrect
Using MainActor.run inside async function ensures UI updates happen on the main thread safely.
4fill in blank
hardFill both blanks to create a MainActor isolated class with a UI update method.
Swift
@[1] class UIHandler { func refresh() [2] { print("Refreshing UI") } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Marking the method as nonisolated which breaks main thread isolation.
Using sync keyword which is invalid in Swift.
✗ Incorrect
Marking the class with @MainActor isolates it to the main thread, and the async method allows asynchronous UI updates.
5fill in blank
hardFill all three blanks to define a MainActor isolated class with an async UI update method and call it safely.
Swift
import Foundation @[1] class Controller { func updateUI() [2] { print("UI Updated") } } func performUpdate() async { let controller = Controller() await controller.[3]() }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to mark the method async.
Calling the async method without await.
Using sync keyword which is invalid.
✗ Incorrect
The class is marked @MainActor to isolate it to the main thread, the method is async to allow awaiting, and the method is called with await.