[swift-dev] [Issue] Collection.distance() works not very well in some situations

Cao, Jiannan frogcjn at 163.com
Sat Dec 2 14:28:07 CST 2017


[Issue] Collection.distance() works not very well in some situations
The question is that, whether the original Collection Protocol requires index from lower to higher (startIndex < endIndex).

If the original Collection Protocol requires index from lower to higher, than this infinity loop should not happen:

> class MyCollectionA : Collection {
>     
>     var startIndex: Int {
>         return 1
>     }
>     
>     var endIndex: Int {
>         return 100
>     }
>     
>     func index(after i: Int) -> Int {
>         return i + 2
>     }
>         
>     subscript(position: Int) -> Void {
>         return ()
>     }
> }
> 
> 
> let a = MyCollectionA()
> a.distance(from: 0, to: 100) // 50
> a.distance(from: 1, to: 100) // !! Infinity Loop
> a.count // !! Infinity Loop

if we assume the index is from lower to higher, the implementation of the distance(from:to:) should use "<" with "while" to count distance

> 
> 
> 
>     var start = start
>     var count: IndexDistance = 0
>     while start < end { // instead of using !=
>       count = count + 1
>       formIndex(after: &start)
>     }
>     return count
>   }




If the original Collection Protocol not requires index from to higher, than the code below should works, but unfortunately, the code in Collection.distance does not allow.


> class MyCollectionB : Collection {
>     
>     var startIndex: Int {
>         return 100
>     }
>     
>     var endIndex: Int {
>         return 0
>     }
>     
>     func index(after i: Int) -> Int {
>         return i - 2
>     }
>     
>     // start, end, index(after i: Int) -> indices: DefaultIndices
>     
>     subscript(position: Int) -> Void {
>         return ()
>     }
> }
> 

> let b = MyCollectionB()
> b.count // !! Fetal Error: Only BidirectionalCollections can have end come before start




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20171203/991d3eab/attachment.html>


More information about the swift-dev mailing list