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