You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Xcode14/iOS16/Swift5.7后编译报错:方法Sendability不符合协议要求

解决Xcode 14/iOS 16/Swift 5.7下NotificationCenterProtocol的Sendability匹配错误

这个错误是因为Swift 5.7强化了并发安全检查,NotificationCenter的addObserver方法里的闭包被标记为@Sendable,但你自定义的NotificationCenterProtocol协议中对应的方法声明没跟上这个变化,导致类型不匹配。

解决步骤:

  • 检查并修正你的NotificationCenterProtocol协议声明,把闭包参数加上@Sendable标记:
    protocol NotificationCenterProtocol {
        func addObserver(forName name: NSNotification.Name?,
                         object obj: Any?,
                         queue: OperationQueue?,
                         using block: @Sendable (Notification) -> Void) -> NSObjectProtocol
    }
    
  • 如果有自定义的协议实现类(比如Mock测试类),实现方法时也要保证闭包参数带有@Sendable:
    class MockNotificationCenter: NotificationCenterProtocol {
        func addObserver(forName name: NSNotification.Name?,
                         object obj: Any?,
                         queue: OperationQueue?,
                         using block: @Sendable (Notification) -> Void) -> NSObjectProtocol {
            // 自定义实现逻辑
            return MockNotificationObserver()
        }
    }
    

原因说明:

Swift 5.7引入的Sendable标记用于标识类型可以安全跨actor/队列传递。NotificationCenter的addObserver方法会将闭包放到指定队列执行,可能涉及跨actor操作,因此系统将该闭包标注为@Sendable。你的协议声明如果没有匹配这个标注,就会触发编译错误。

内容的提问来源于stack exchange,提问作者Nikolay Suvandzhiev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:20:56