11.2 C
Canberra
Wednesday, December 3, 2025

ios – How can I migrate NotificationCenter code to Swift 6 concurrency?


I’m migrating a NotificationManager class to Swift 6. This class is a small utility wrapper round NotificationCenterand has a technique that lets customers register a notification that can triggerunless the object is the same as a selected NSObjectworth.

For instance:

supervisor.registerObserver(for: title, forObject: nil, ignoreIfSentFrom: self) {
  // run this code _only_ if the sender wasn't self 
}

The strategy seems to be like this:

  non-public func registerObserver(_ title: NSNotification.Title, forObject object: AnyObject?,
                                ignoreIfSentFrom ignoredObject: NSObject, block: @Sendable @MainActor @escaping (Notification) -> ())
  {
    let newToken = NotificationCenter.default.addObserver(forName: title, object: object, queue: nil) { word in
      guard (word.object as AnyObject) !== ignoredObject else { return }
      
      Process { @MainActor in
        block(word)
      }
    }
    
    observerTokens.append(newToken)
  }

I get two errors right here that I can’t determine find out how to resolve:

  • Seize of 'ignoredObject' with non-Sendable sort 'NSObject?' in a '@Sendable' closure (on the guard line)
  • Sending 'word' dangers inflicting knowledge races; that is an error within the Swift 6 language mode (for block(word))

Is it nonetheless attainable to implement this concept with Swift 6 strict concurrency? It seems to be like Notification is neither Sendablenor @MainActor and since I don’t personal that sort, I’m at a loss for find out how to make this work.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles