Ios 如何将索引(of:)与[SomeProtocol]一起使用?

Ios 如何将索引(of:)与[SomeProtocol]一起使用?,ios,swift,protocols,Ios,Swift,Protocols,我有很多类都是UIView。有些符合特定的协议。我有一个由这些特殊元素组成的数组,但是我不能在这个数组上调用index(of:)(这段代码可以粘贴到游戏中): 错误是: cannot invoke 'index' with an argument list of type '(of: BlueView)' 无法调用该函数,因为协议ViewWithColor不符合equalable。我真的必须实现equalable吗?或者有更好的方法吗?您可以使用闭包语法并检查类型: let index1 =

我有很多类都是UIView。有些符合特定的协议。我有一个由这些特殊元素组成的数组,但是我不能在这个数组上调用index(of:)(这段代码可以粘贴到游戏中):

错误是:

cannot invoke 'index' with an argument list of type '(of: BlueView)'

无法调用该函数,因为协议ViewWithColor不符合
equalable
。我真的必须实现equalable吗?或者有更好的方法吗?

您可以使用闭包语法并检查类型:

let index1 = allViews.index(where: {$0 is BlueView})
let index2 = viewsWithColorArray.index(where: {$0 is BlueView})

正如@vadian所说,您可以使用带有闭包的
index
版本。在本例中,您正在查找一个特定实例,因此使用
索引(其中:{$0===blueView})

=
运算符:

返回一个布尔值,该值指示两个引用是否指向 相同的对象实例

此外,您还需要将协议
ViewWithColor
a
class
协议,因为
==
仅适用于类实例

protocol ViewWithColor: class {}

class BlackView: UIView {}
class WhiteView: UIView {}
class BlueView: UIView, ViewWithColor {}
class GreenView: UIView, ViewWithColor {}
class YellowView: UIView, ViewWithColor {}

let blackView = BlackView()
let whiteView = WhiteView()
let blueView = BlueView()
let greenView = GreenView()
let yellowView = YellowView()

let allViews = [blackView, whiteView, blueView, greenView, yellowView]
let viewsWithColorArray: [ViewWithColor] = [blueView, greenView, yellowView]

let index1 = allViews.index(where: { $0 === blueView })
print(index1 ?? -1)

好主意,但对我来说不行。对于index2,我不是在寻找BlueView类型的所有视图,而是在寻找一个特定的实例。视图中可能有多个BlueView实例,语法为
index(of
index)(其中
成功后,您将始终获得与条件匹配的第一次出现的索引。
索引(其中:{$0==BlueView})如何
是否要查找特定实例?@vacawama错误:“BlueView”不能隐式转换为“AnyHashable”;是否要使用“as”显式转换?
protocol ViewWithColor: class {}

class BlackView: UIView {}
class WhiteView: UIView {}
class BlueView: UIView, ViewWithColor {}
class GreenView: UIView, ViewWithColor {}
class YellowView: UIView, ViewWithColor {}

let blackView = BlackView()
let whiteView = WhiteView()
let blueView = BlueView()
let greenView = GreenView()
let yellowView = YellowView()

let allViews = [blackView, whiteView, blueView, greenView, yellowView]
let viewsWithColorArray: [ViewWithColor] = [blueView, greenView, yellowView]

let index1 = allViews.index(where: { $0 === blueView })
print(index1 ?? -1)
2
let index2 = viewsWithColorArray.index(where: { $0 === blueView })
print(index2 ?? -1)
0