@@ -701,16 +701,11 @@ public protocol Collection: Sequence where SubSequence: Collection {
701
701
702
702
/// Returns the distance between two indices.
703
703
///
704
- /// Unless the collection conforms to the `BidirectionalCollection` protocol,
705
- /// `start` must be less than or equal to `end`.
706
- ///
707
704
/// - Parameters:
708
705
/// - start: A valid index of the collection.
709
706
/// - end: Another valid index of the collection. If `end` is equal to
710
707
/// `start`, the result is zero.
711
- /// - Returns: The distance between `start` and `end`. The result can be
712
- /// negative only if the collection conforms to the
713
- /// `BidirectionalCollection` protocol.
708
+ /// - Returns: The distance between `start` and `end`.
714
709
///
715
710
/// - Complexity: O(1) if the collection conforms to
716
711
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
@@ -962,30 +957,34 @@ extension Collection {
962
957
963
958
/// Returns the distance between two indices.
964
959
///
965
- /// Unless the collection conforms to the `BidirectionalCollection` protocol,
966
- /// `start` must be less than or equal to `end`.
967
- ///
968
960
/// - Parameters:
969
961
/// - start: A valid index of the collection.
970
962
/// - end: Another valid index of the collection. If `end` is equal to
971
963
/// `start`, the result is zero.
972
- /// - Returns: The distance between `start` and `end`. The result can be
973
- /// negative only if the collection conforms to the
974
- /// `BidirectionalCollection` protocol.
964
+ /// - Returns: The distance between `start` and `end`.
975
965
///
976
966
/// - Complexity: O(1) if the collection conforms to
977
967
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
978
968
/// resulting distance.
979
969
@_inlineable
980
970
public func distance( from start: Index , to end: Index ) -> Int {
981
- _precondition ( start <= end,
982
- " Only BidirectionalCollections can have end come before start " )
983
-
984
- var start = start
971
+ var _start : Index
972
+ let _end : Index
973
+ let step : Int
974
+ if start > end {
975
+ _start = end
976
+ _end = start
977
+ step = - 1
978
+ }
979
+ else {
980
+ _start = start
981
+ _end = end
982
+ step = 1
983
+ }
985
984
var count = 0
986
- while start != end {
987
- count = count + 1
988
- formIndex ( after: & start )
985
+ while _start != _end {
986
+ count += step
987
+ formIndex ( after: & _start )
989
988
}
990
989
return count
991
990
}
0 commit comments