Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is .successor() in swift? [closed]

Tags:

ios

swift

Can someone explain what someVar.successor() is? Apple documentation says "Returns the next consecutive value after self.". I don't understand its implementation meaning.

Thanks.

like image 509
Kiran Thapa Avatar asked Jan 06 '15 07:01

Kiran Thapa


2 Answers

The successor() method returns the next value after the current one (if any, if the current value is 0 then calling successor() will return 1 and so on)

A typical successor() implementation will look like:

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.

Read more about this here

like image 169
Midhun MP Avatar answered Nov 14 '22 22:11

Midhun MP


Instead of adding 1, we can call successor() on index.

For example this :

func naturalIndexOfItem(item: Item) -> Int? {
    if let index = indexOfItem(item) {
        return index + 1
    } else {
        return nil
    }
}

Is equal to this:

func naturalIndexOfItem(item: Item) -> Int? {
    if let index = indexOfItem(item) {
        return index.successor()
    } else {
        return nil
    }
}
like image 28
Prajeet Shrestha Avatar answered Nov 14 '22 23:11

Prajeet Shrestha