我有一堆 UIView 类。有些符合特定的协议(protocol)。我有一个包含这些特定数组的数组,但我无法在此数组上调用 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)'
无法调用该函数,因为协议(protocol) ViewWithColor 不符合 Equatable
。我真的必须实现 equatable 吗?或者有更好的方法吗?
最佳答案
正如@vadian 所说,您可以使用带有闭包的index
版本。在这种情况下,您要查找特定实例,因此请使用 index(where: { $0 === blueView })
。
===
运算符:
Returns a Boolean value indicating whether two references point to the same object instance.
此外,您需要使协议(protocol) ViewWithColor
成为 class
协议(protocol),因为 ===
仅适用于类实例。
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
关于ios - 如何使用索引(:) with [SomeProtocol]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830422/