I’m migrating a NotificationManager class to Swift 6. This class is a small utility wrapper around NotificationCenterand has a method that lets users register a notification that will triggerunless the object is equal to a particular NSObjectvalue.
For example:
manager.registerObserver(for: name, forObject: nil, ignoreIfSentFrom: self) {
// run this code _only_ if the sender wasn't self
}
The method looks like this:
private func registerObserver(_ name: NSNotification.Name, forObject object: AnyObject?,
ignoreIfSentFrom ignoredObject: NSObject, block: @Sendable @MainActor @escaping (Notification) -> ())
{
let newToken = NotificationCenter.default.addObserver(forName: name, object: object, queue: nil) { note in
guard (note.object as AnyObject) !== ignoredObject else { return }
Task { @MainActor in
block(note)
}
}
observerTokens.append(newToken)
}
I get two errors here that I can’t figure out how to resolve:
Capture of 'ignoredObject' with non-Sendable type 'NSObject?' in a '@Sendable' closure(on theguardline)Sending 'note' risks causing data races; this is an error in the Swift 6 language mode(forblock(note))
Is it still possible to implement this idea with Swift 6 strict concurrency? It looks like Notification is neither Sendablenor @MainActor and since I don’t own that type, I’m at a loss for how to make this work.