ios - 如何使用索引(:) with [SomeProtocol]?

标签 ios swift protocols

我有一堆 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/

相关文章:

ios - 动画 UICollectionView 页脚高度

c++ - 在 C++ 中实现固定字节串行协议(protocol)的最佳实践?

ios - 协议(protocol)方法如何在类中设置变量?

ios - RestKit - 从 RKRequestDescriptor 中排除具有 nil 值的属性映射

ios - 如何在 Xcode 的项目目录中打开 Playground?

ios - 如何以任意时间偏移开始交互式动画?

ios - 如何在 appearance() 中更改 UIButton titlelabel 字体样式和大小?

iOS:返回上一个 View

Swift:协议(protocol)中属性的默认值

ios - 重新显示 View 时,另一个表的单元格中的动态大小表不会调整大小