Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

xcode - Find index of object in an array of type [SomeProtocol]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...