问题描述
我有一个名为subscribers 的数组,用于存储符合JABPanelChangeSubscriber 协议的对象.协议声明为
I have an array called subscribers that stores objects which conform to the protocol JABPanelChangeSubscriber. The protocol is declared as
public protocol JABPanelChangeSubscriber {
}
我的数组被声明为:
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)
}
}
不幸的是,JABPanelChangeSubscriber 不是 Equatable,我不知道如何使它成为 Equatable,所以 find 方法给了我一个错误.任何人都可以帮助我解决问题或提出不同方法的建议吗?
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?
谢谢
推荐答案
假设实现你的协议的所有类型都是引用类型(类),你可以将协议声明为类协议"
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 alreadycontains an element pointing to the same instance as the given argument:
public func addSubscriber(subscriber: JABPanelChangeSubscriber) {
if !contains(subscribers, { $0 === subscriber } ) {
subscribers.append(subscriber)
}
}
这篇关于在 [SomeProtocol] 类型的数组中查找对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!