0
0
Swiftprogramming~10 mins

Actors vs locks decision in Swift - Interactive Practice

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'
Aenum
Bclass
Cstruct
DCounter
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' or 'struct' instead of an actor name.
2fill in blank
medium

Complete the code to call an async method on an actor instance.

Swift
let counter = Counter()
Task {
    await counter.[1]()
}
Drag options to blanks, or click blank then click option'
Aincrement
BincrementSync
CincrementNow
DincrementLater
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names that imply synchronous calls which are not allowed on actors.
3fill in blank
hard

Fix the error in the code to safely access shared data using a lock.

Swift
class SafeCounter {
    private var count = 0
    private let lock = NSLock()

    func increment() {
        [1].lock()
        count += 1
        lock.unlock()
    }
}
Drag options to blanks, or click blank then click option'
Acounter
Block
Cself
DNSLock
Attempts:
3 left
💡 Hint
Common Mistakes
Calling lock() on 'self' or class name instead of the lock instance.
4fill in blank
hard

Fill in the blank to create a dictionary filter that selects keys with values greater than 10.

Swift
let filtered = dictionary.filter { $0.value [1] 10 }.map { ($0.key, $0.value) }
let result = Dictionary(uniqueKeysWithValues: filtered) // Result dictionary
Drag options to blanks, or click blank then click option'
A!=
B<
C>
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '==' which filter wrong values.
5fill in blank
hard

Fill all three blanks to create an actor method that safely increments and returns the count.

Swift
actor Counter {
    private var count = 0

    func incrementAndGet() async -> Int {
        [1]
        count += 1
        let current = [2]
        [3]
        return current
    }
}
Drag options to blanks, or click blank then click option'
Aawait Task.sleep(nanoseconds: 0)
Bcount
Cawait Task.yield()
Dcount + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning wrong values or missing async suspension points.