@@ -285,12 +285,17 @@ public protocol RangeReplaceableCollection: Collection
285
285
/// Customization point for `removeLast()`. Implement this function if you
286
286
/// want to replace the default implementation.
287
287
///
288
+ /// The collection must not be empty.
289
+ ///
288
290
/// - Returns: A non-nil value if the operation was performed.
289
291
mutating func _customRemoveLast( ) -> Element ?
290
292
291
293
/// Customization point for `removeLast(_:)`. Implement this function if you
292
294
/// want to replace the default implementation.
293
295
///
296
+ /// - Parameter n: The number of elements to remove from the collection.
297
+ /// `n` must be greater than or equal to zero and must not exceed the
298
+ /// number of elements in the collection.
294
299
/// - Returns: `true` if the operation was performed.
295
300
mutating func _customRemoveLast( _ n: Int ) -> Bool
296
301
@@ -802,7 +807,12 @@ extension RangeReplaceableCollection
802
807
803
808
@inlinable
804
809
public mutating func _customRemoveLast( _ n: Int ) -> Bool {
805
- self = self [ startIndex..< index ( endIndex, offsetBy: - n) ]
810
+ guard let end = index ( endIndex, offsetBy: - n, limitedBy: startIndex)
811
+ else {
812
+ _preconditionFailure (
813
+ " Can't remove more items from a collection than it contains " )
814
+ }
815
+ self = self [ startIndex..< end]
806
816
return true
807
817
}
808
818
}
@@ -866,13 +876,17 @@ extension RangeReplaceableCollection where Self: BidirectionalCollection {
866
876
public mutating func removeLast( _ k: Int ) {
867
877
if k == 0 { return }
868
878
_precondition ( k >= 0 , " Number of elements to remove should be non-negative " )
869
- _precondition ( count >= k,
870
- " Can't remove more items from a collection than it contains " )
871
879
if _customRemoveLast ( k) {
872
880
return
873
881
}
874
882
let end = endIndex
875
- removeSubrange ( index ( end, offsetBy: - k) ..< end)
883
+ guard let start = index ( end, offsetBy: - k, limitedBy: startIndex)
884
+ else {
885
+ _preconditionFailure (
886
+ " Can't remove more items from a collection than it contains " )
887
+ }
888
+
889
+ removeSubrange ( start..< end)
876
890
}
877
891
}
878
892
@@ -936,13 +950,16 @@ where Self: BidirectionalCollection, SubSequence == Self {
936
950
public mutating func removeLast( _ k: Int ) {
937
951
if k == 0 { return }
938
952
_precondition ( k >= 0 , " Number of elements to remove should be non-negative " )
939
- _precondition ( count >= k,
940
- " Can't remove more items from a collection than it contains " )
941
953
if _customRemoveLast ( k) {
942
954
return
943
955
}
944
956
let end = endIndex
945
- removeSubrange ( index ( end, offsetBy: - k) ..< end)
957
+ guard let start = index ( end, offsetBy: - k, limitedBy: startIndex)
958
+ else {
959
+ _preconditionFailure (
960
+ " Can't remove more items from a collection than it contains " )
961
+ }
962
+ removeSubrange ( start..< end)
946
963
}
947
964
}
948
965
0 commit comments