swift 中的 .successor() 是什么?

What is .successor() in swift?

谁能解释一下 someVar.successor() 是什么?苹果文档说 "Returns the next consecutive value after self."。我不明白它的实现意义。

谢谢。

我们可以在索引上调用 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
    }
}

successor() 方法 return 是当前值之后的下一个值(如果有的话,如果当前值为 0 那么调用 successor() 将 return 1 并且等等)

典型的 successor() 实现如下所示:

class ForWardIndexDemo: ForwardIndex
{
    private var _myIndex = 0
    init(index: Int)
    {
       _myIndex = index;
    }

    func successor() -> ForWardIndexDemo
    {
       return ForWardIndexDemo(index:_myIndex++)
    }
}

The collection associated type IndexType specifies which type is used to index the collection. Any type that implements ForwardIndex can be used as the IndexType.

The ForwardIndex is an index that can only be incremented, for example a forward index of value 0 can be incremented to 1,2,3 etc…, This protocol internally inherits from Equatable and _Incrementable protocols. In order to adhere to the ForwardIndex protocol successor() -> Self method and the Equatable protocols must be implemented.

阅读更多相关内容here