如何使用[SomeProtocol]索引(of :)?

时间:2017-03-16 09:47:29

标签: ios swift protocols

我有一堆UIViews的课程。一些符合特定协议。我有一些这些特殊的数组,但是我不能在这个数组上调用index(of :)(这段代码可以粘贴到Playground中):

import UIKit

protocol ViewWithColor {}

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(of: blueView)
let index2 = viewsWithColorArray.index(of: blueView)

错误是:

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

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

2 个答案:

答案 0 :(得分:4)

正如@vadian所说,你可以使用需要关闭的index版本。在这种情况下,您正在寻找特定实例,因此请使用index(where: { $0 === blueView })

===运算符:

  

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

此外,您需要使协议ViewWithColor成为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)
2
let index2 = viewsWithColorArray.index(where: { $0 === blueView })
print(index2 ?? -1)
0

答案 1 :(得分:3)

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

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