Hi all,
I'm running into a Swift Concurrency issue and would appreciate some help understanding what's going on.
I have a protocol and an actor set up like this:
protocol PersistenceListener: AnyObject {
func persistenceDidUpdate(key: String, newValue: Any?)
}
actor Persistence {
func addListener(_ listener: PersistenceListener) {
listeners.add(listener)
}
/// Removes a listener.
func removeListener(_ listener: PersistenceListener) {
listeners.remove(listener)
}
// MARK: - Private Properties
private var listeners = NSHashTable<AnyObject>.weakObjects()
// MARK: - Private Methods
/// Notifies all registered listeners on the main actor.
private func notifyListeners(key: String, value: Any?) async {
let currentListeners = listeners.allObjects.compactMap { $0 as? PersistenceListener }
for listener in currentListeners {
await MainActor.run {
listener.persistenceDidUpdate(key: key, newValue: value)
}
}
}
}
When I compile this code, I get a concurrency error:
"Sending 'listener' risks causing data races"
Selecting any option will automatically load the page