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"
public protocol JABPanelChangeSubscriber : class {
}
and use the identity operator === to check if the array already
contains an element pointing to the same instance as the given argument:
public func addSubscriber(subscriber: JABPanelChangeSubscriber) {
if !contains(subscribers, { $0 === subscriber } ) {
subscribers.append(subscriber)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With