在[SomeProtocol]类型的数组中查找对象的索引

时间:2015-05-20 08:27:15

标签: arrays xcode swift protocols iequatable

我有一个名为subscriber的数组,它存储符合JABPanelChangeSubscriber协议的对象。该协议声明为

public protocol JABPanelChangeSubscriber {

}

我的数组声明为:

var subscribers = [JABPanelChangeSubscriber]()

现在我需要实现一个方法来将订阅者添加到列表中,但首先必须检查该订阅者之前是否已经添加过。

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方法给了我一个错误。任何人都可以帮我解决问题或建议采用不同的方法吗?

由于

2 个答案:

答案 0 :(得分:3)

假设实现协议的所有类型都是引用类型 (类),您可以将协议声明为"类协议"

select * from table_name where value >=4000 and rownum = 1;

并使用标识运算符public protocol JABPanelChangeSubscriber : class { } 来检查数组是否已经存在 包含指向与给定参数相同的实例的元素:

===

答案 1 :(得分:0)

isEqualTo(:)要求添加到JABPanelChangeSubscriber协议

public protocol JABPanelChangeSubscriber {
    func isEqualTo(other: JABPanelChangeSubscriber) -> Bool
}

使用JABPanelChangeSubscriber要求扩展到Self协议

extension JABPanelChangeSubscriber where Self: Equatable {
   func isEqualTo(other: JABPanelChangeSubscriber) -> Bool {
      guard let other = other as? Self else { return false }
        return self == other
   }
}
  

请记住使对象符合Equatable协议

class SomeClass: Equatable {}
func == (lhs: SomeClass, rhs: SomeClass) -> Bool {
//your code here
//you could use `===` operand
}

struct SomeStruct: Equatable {}
func == (lhs: SomeStruct, rhs: SomeStruct) -> Bool {
//your code here
}

然后找到索引

func indexOf(object: JABPanelChangeSubscriber) -> Int? {
    return subcribers.indexOf({ $0.isEqualTo(object) })
}

如果要在将对象添加到数组之前检查对象是否存在

func addSubscriber(subscriber: JABPanelChangeSubscriber) {
    if !subscribers.contains({ $0.isEqualTo(subscriber) }) {
        subscribers.append(subscriber)
    }
}