I have an array called subscribers that stores objects which conform to the protocol JABPanelChangeSubscriber. The protocol is declared as
public protocol JABPanelChangeSubscriber {
}
and my array is declared as:
var subscribers = [JABPanelChangeSubscriber]()
Now I need to implement a method to add a subscriber to the list, but it first has to check that that subscriber has not already been added before.
public func addSubscriber(subscriber: JABPanelChangeSubscriber) {
if subscribers.find(subscriber) == nil { // This ensures that the subscriber has never been added before
subscribers.append(subscriber)
}
}
Unfortunately, JABPanelChangeSubscriber is not Equatable, and I can't figure out how to make it Equatable, so the find method is giving me an error. Can anyone help me out with a fix or with a suggestion for a different approach?
Thanks
Assuming that all types implementing your protocol are reference types (classes), you can declare the protocol as a "class protocol"
and use the identity operator
===
to check if the array already contains an element pointing to the same instance as the given argument:Add
isEqualTo(:)
requirement toJABPanelChangeSubscriber
protocolExtension to
JABPanelChangeSubscriber
protocol withSelf
requirementThen find the index
If you want to check the existence of an object before adding them to the array