0
0
Swiftprogramming~10 mins

Global actors (@MainActor) 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 as running on the main actor.

Swift
@[1]
func updateUI() {
    print("UI updated")
}
Drag options to blanks, or click blank then click option'
AMainActor
BGlobalActor
CUIActor
DBackgroundActor
Attempts:
3 left
💡 Hint
Common Mistakes
Using @GlobalActor instead of @MainActor
Forgetting the '@' symbol before MainActor
Using unrelated actor names
2fill in blank
medium

Complete the code to declare a global actor named MyActor.

Swift
@globalActor
struct [1] {
    static let shared = MyActor()
}
Drag options to blanks, or click blank then click option'
AYourActor
BGlobalActor
CMainActor
DMyActor
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name than the shared instance
Confusing with built-in actors like MainActor
3fill in blank
hard

Fix the error in the code to ensure the function runs on the main actor.

Swift
[1]
func updateData() async {
    print("Data updated")
}
Drag options to blanks, or click blank then click option'
A@MainActor
Basync
C@globalActor
D@UIActor
Attempts:
3 left
💡 Hint
Common Mistakes
Using @globalActor which is not a valid attribute
Placing async incorrectly
Using a non-existent actor like @UIActor
4fill in blank
hard

Fill both blanks to declare a global actor and use it on a function.

Swift
@globalActor
struct [1] {
    static let shared = [1]()
}

@[2]
func performTask() {
    print("Task performed")
}
Drag options to blanks, or click blank then click option'
ACustomActor
BMainActor
DGlobalActor
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for struct and shared instance
Using @MainActor instead of the custom actor
5fill in blank
hard

Fill all three blanks to create a global actor, mark a class with it, and declare an async function.

Swift
@globalActor
struct [1] {
    static let shared = [1]()
}

[2]
class DataManager {
    func fetchData() [3] {
        print("Fetching data")
    }
}
Drag options to blanks, or click blank then click option'
ANetworkActor
C@NetworkActor
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting '@' before the actor name on the class
Mismatching struct and shared instance names
Omitting async keyword on the function