0
0
Swiftprogramming~10 mins

MainActor for UI work in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AUIActor
BBackgroundActor
CMainActor
DAsyncActor
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong actor attribute that does not guarantee main thread execution.
2fill in blank
medium

Complete 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'
ATask.detached
BDispatchQueue.global().async
CDispatchQueue.main.async
DMainActor.run
Attempts:
3 left
💡 Hint
Common Mistakes
Using DispatchQueue.global() which runs on a background thread.
Using Task.detached which runs detached from any actor.
3fill in blank
hard

Fix 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'
AMainActor.run
BDispatchQueue.global().async
CTask.detached
DDispatchQueue.main.async
Attempts:
3 left
💡 Hint
Common Mistakes
Using DispatchQueue.global() which runs on a background thread.
Using Task.detached which runs detached from any actor.
4fill in blank
hard

Fill 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'
AMainActor
Basync
Cnonisolated
Dsync
Attempts:
3 left
💡 Hint
Common Mistakes
Marking the method as nonisolated which breaks main thread isolation.
Using sync keyword which is invalid in Swift.
5fill in blank
hard

Fill 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'
AMainActor
Basync
CupdateUI
Dsync
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to mark the method async.
Calling the async method without await.
Using sync keyword which is invalid.