Junior — Middle
Is it possible to use the synchronized keyword directly to protect a single variable?
sobes.tech AI
Answer from AI
In Swift (iOS), the keyword synchronized is absent; it exists in Java. Therefore, you cannot directly use synchronized to protect a specific variable.
To protect access to a variable in Swift, other synchronization mechanisms are usually used, such as:
- Using
DispatchQueuewith barriers or serial queues. - Using
NSLockor other locking objects.
Example of protecting a variable using DispatchQueue:
class ThreadSafeCounter {
private var value = 0
private let queue = DispatchQueue(label: "com.example.counter")
func increment() {
queue.sync {
value += 1
}
}
func getValue() -> Int {
return queue.sync { value }
}
}
Thus, in iOS, to protect variables, you should use appropriate synchronization mechanisms rather than the synchronized keyword.