找对象的索引类型的数组[SomeProtocol] [英] Find index of object in an array of type [SomeProtocol]

查看:219
本文介绍了找对象的索引类型的数组[SomeProtocol]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储作为符合协议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 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)
    }
}

这篇关于找对象的索引类型的数组[SomeProtocol]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆