@@ -798,6 +798,24 @@ extension RangeReplaceableCollection
798
798
}
799
799
800
800
extension RangeReplaceableCollection where Self : BidirectionalCollection {
801
+ /// Removes and returns the last element of the collection.
802
+ ///
803
+ /// Calling this method may invalidate all saved indices of this
804
+ /// collection. Do not rely on a previously stored index value after
805
+ /// altering a collection with any operation that can change its length.
806
+ ///
807
+ /// - Returns: The last element of the collection if the collection is not
808
+ /// empty; otherwise, `nil`.
809
+ ///
810
+ /// - Complexity: O(1)
811
+ @_inlineable
812
+ public mutating func popLast( ) -> Element ? {
813
+ if isEmpty { return nil }
814
+ // duplicate of removeLast logic below, to avoid redundant precondition
815
+ if let result = _customRemoveLast ( ) { return result }
816
+ return remove ( at: index ( before: endIndex) )
817
+ }
818
+
801
819
/// Removes and returns the last element of the collection.
802
820
///
803
821
/// The collection must not be empty.
@@ -813,9 +831,8 @@ extension RangeReplaceableCollection where Self : BidirectionalCollection {
813
831
@discardableResult
814
832
public mutating func removeLast( ) -> Element {
815
833
_precondition ( !isEmpty, " Can't remove last element from an empty collection " )
816
- if let result = _customRemoveLast ( ) {
817
- return result
818
- }
834
+ // NOTE if you change this implementation, change popLast above as well
835
+ if let result = _customRemoveLast ( ) { return result }
819
836
return remove ( at: index ( before: endIndex) )
820
837
}
821
838
0 commit comments