Skip to content

Commit 21fcfdc

Browse files
committed
Merge pull request #2670 from apple/stdlib-se-0078-reverse
stdlib: implement reverse() as proposed in SE-0078
2 parents 993f84c + 296e2ae commit 21fcfdc

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift.gyb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,20 @@ if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .none {
685685
}
686686
}
687687

688+
//===----------------------------------------------------------------------===//
689+
// reverse()
690+
//===----------------------------------------------------------------------===//
691+
692+
self.test("\(testNamePrefix).reverse()") {
693+
for test in reverseTests {
694+
var c = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
695+
c.reverse()
696+
expectEqual(
697+
test.expected, c.map { extractValue($0).value },
698+
stackTrace: SourceLocStack().with(test.loc))
699+
}
700+
}
701+
688702
//===----------------------------------------------------------------------===//
689703

690704
} // addMutableBidirectionalCollectionTests

stdlib/public/core/Reverse.swift

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//===--- Reverse.swift - Lazy sequence reversal ---------------------------===//
1+
//===--- Reverse.swift - Sequence and collection reversal -----------------===//
22
//
33
// This source file is part of the Swift.org open source project
44
//
@@ -10,6 +10,28 @@
1010
//
1111
//===----------------------------------------------------------------------===//
1212

13+
extension MutableCollection where Self : BidirectionalCollection {
14+
/// Reverses the elements of the collection in place.
15+
///
16+
/// var characters: [Character] = ["C", "a", "f", "é"]
17+
/// characters.reverse()
18+
/// print(cafe.characters)
19+
/// // Prints "["é", "f", "a", "C"]
20+
///
21+
/// - Complexity: O(*n*), where *n* is the number of elements in the
22+
/// collection.
23+
public mutating func reverse() {
24+
if isEmpty { return }
25+
var f = startIndex
26+
var l = index(before: endIndex)
27+
while f < l {
28+
swap(&self[f], &self[l])
29+
formIndex(after: &f)
30+
formIndex(before: &l)
31+
}
32+
}
33+
}
34+
1335
// FIXME(ABI)(compiler limitation): we should have just one type,
1436
// `ReversedCollection`, that has conditional conformances to
1537
// `RandomAccessCollection`, and possibly `MutableCollection` and

0 commit comments

Comments
 (0)