有人可以解释someVar.successor()是什么吗? Apple文档说"返回self
之后的下一个连续值。"。我不了解它的实现意义。
感谢。
答案 0 :(得分:9)
successor()
方法返回当前值之后的下一个值(如果有,如果当前值为0,则调用successor()
将返回1,依此类推)
典型的successor()实现将如下所示:
class ForWardIndexDemo: ForwardIndex
{
private var _myIndex = 0
init(index: Int)
{
_myIndex = index;
}
func successor() -> ForWardIndexDemo
{
return ForWardIndexDemo(index:_myIndex++)
}
}
集合关联类型IndexType指定使用的类型 索引集合。任何实现ForwardIndex的类型都可以 用作IndexType。
例如,ForwardIndex是一个只能递增的索引 值为0的正向索引可以递增到1,2,3等...,这 protocol内部继承自Equatable和_Incrementable 协议。为了遵守ForwardIndex协议的继承者() - >必须实现自我方法和Equatable协议。
详细了解此here
答案 1 :(得分:6)
我们可以在索引上调用successor(),而不是添加1。
例如:
func naturalIndexOfItem(item: Item) -> Int? {
if let index = indexOfItem(item) {
return index + 1
} else {
return nil
}
}
等于:
func naturalIndexOfItem(item: Item) -> Int? {
if let index = indexOfItem(item) {
return index.successor()
} else {
return nil
}
}