diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift index 98b6cc89029b5..c702e3c5d5530 100644 --- a/stdlib/public/core/BidirectionalCollection.swift +++ b/stdlib/public/core/BidirectionalCollection.swift @@ -342,9 +342,12 @@ extension BidirectionalCollection where SubSequence == Self { public mutating func removeLast(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[startIndex..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[index(startIndex, offsetBy: k).. Element? /// Customization point for `removeLast(_:)`. Implement this function if you /// want to replace the default implementation. /// + /// - Parameter n: The number of elements to remove from the collection. + /// `n` must be greater than or equal to zero and must not exceed the + /// number of elements in the collection. /// - Returns: `true` if the operation was performed. mutating func _customRemoveLast(_ n: Int) -> Bool @@ -591,9 +596,10 @@ extension RangeReplaceableCollection { public mutating func removeFirst(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it has") - let end = index(startIndex, offsetBy: k) + guard let end = index(startIndex, offsetBy: k, limitedBy: endIndex) else { + _preconditionFailure( + "Can't remove more items from a collection than it has") + } removeSubrange(startIndex..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[index(startIndex, offsetBy: k).. Bool { - self = self[startIndex..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") if _customRemoveLast(k) { return } let end = endIndex - removeSubrange(index(end, offsetBy: -k)..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") if _customRemoveLast(k) { return } let end = endIndex - removeSubrange(index(end, offsetBy: -k)..