我试图在协议扩展中使用 "objectWillChange.send()" 但它不起作用,知道为什么吗?

I'm trying to use "objectWillChange.send()" in an protocol extension but it's not working, any idea why?

我有一个显示玩家列表的 SwiftUI 导航视图。我设计的视图模型协议如下。


protocol PlayerListStateProviding: ObservableObject {
    var players: [PlayerModel] { get set }
}

protocol PlayerListDeleting {
    var moc: NSManagedObjectContext { get set }
    func delete(at indexSet: IndexSet)
}

extension PlayerListDeleting where Self: PlayerListStateProviding {
    func delete(at indexSet: IndexSet) {
        moc.delete(players.remove(at: indexSet.first!))
        objectWillChange.send() // this doesn't compile with the following error "Value of type 'Self.ObjectWillChangePublisher' has no member 'send'"
    }
}

我不确定这个错误是什么以及如何避免它。但是,当我删除扩展并创建具体 class 时,我可以毫无问题地发送信号。

要在协议中使用默认的可观察对象发布者,您应该将其限制为相应的类型(因为它是 ObservableObject 的扩展),如

extension PlayerListDeleting where Self: PlayerListStateProviding,  
               Self.ObjectWillChangePublisher == ObservableObjectPublisher {
    func delete(at indexSet: IndexSet) {
        moc.delete(players.remove(at: indexSet.first!))
        objectWillChange.send()
    }
}

backup