升级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
相关产品推荐
相关产品推荐

