Search code examples
protocolsswiftui

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


I've a SwiftUI navigation view showing a list of players. I designed the view model protocols as follows.


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'"
    }
}

I'm not sure what this error is and how to avoid it. However when I remove the extension and create concrete class, I could send the signal with no problem.


Solution

  • To use default observable object publisher in protocol you should limit it to corresponding type (because it is in extension to ObservableObject), as in

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