0
0
Swiftprogramming~10 mins

Why actors prevent data races in Swift - Test Your Understanding

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

Complete the code to declare an actor in Swift.

Swift
actor [1] {
    var count = 0
}
Drag options to blanks, or click blank then click option'
Aclass
BCounter
Cstruct
Denum
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' or 'struct' instead of 'actor' to declare an actor.
2fill in blank
medium

Complete the code to safely increment the count inside the actor.

Swift
actor Counter {
    var count = 0
    func increment() {
        [1]
    }
}
Drag options to blanks, or click blank then click option'
Aself.count = count + 1
Bcount += 1
Ccount = count + 1
Dself.count += 1
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting 'self.' before 'count' inside the actor method.
3fill in blank
hard

Fix the error in calling the actor's method asynchronously.

Swift
let counter = Counter()
Task {
    await [1].increment()
}
Drag options to blanks, or click blank then click option'
Acounter
BCounter
Cself
Dincrement
Attempts:
3 left
💡 Hint
Common Mistakes
Using the actor type name instead of the instance to call the method.
4fill in blank
hard

Fill both blanks to define an actor with a method that returns the count.

Swift
actor [1] {
    var count = 0
    func getCount() async -> [2] {
        return count
    }
}
Drag options to blanks, or click blank then click option'
ASafeCounter
BInt
CString
DDouble
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong return type like String or Double for the count.
5fill in blank
hard

Fill all three blanks to create an actor that prevents data races by isolating state and providing safe access.

Swift
actor [1] {
    private var value: [2] = 0
    func updateValue(to newValue: [3]) {
        value = newValue
    }
}
Drag options to blanks, or click blank then click option'
ADataGuard
BInt
CString
DDouble
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the variable and method parameter.