Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 830
M.Serag Avatar asked Jan 04 '20 09:01

M.Serag


1 Answers

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()
    }
}

backup

like image 121
Asperi Avatar answered Sep 22 '22 11:09

Asperi