Skip to content

Commit eb7c39b

Browse files
committed
[stdlib] Add String.subscript(_: ClosedRange<Index>) (#2653)
Fixes [SR-1596](https://bugs.swift.org/browse/SR-1596).
1 parent 5c83792 commit eb7c39b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

stdlib/public/core/StringRangeReplaceableCollection.swift.gyb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ extension String {
8484
public subscript(bounds: Range<Index>) -> String {
8585
return String(characters[bounds])
8686
}
87+
88+
/// Accesses the text in the given range.
89+
///
90+
/// - Complexity: O(*n*) if the underlying string is bridged from
91+
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
92+
public subscript(bounds: ClosedRange<Index>) -> String {
93+
return String(characters[bounds])
94+
}
8795
}
8896

8997
public func == (lhs: String.Index, rhs: String.Index) -> Bool {

validation-test/stdlib/String.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,22 @@ StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") {
205205
acceptor[i]
206206
}
207207

208+
StringTests.test("String/subscript(_:Range)") {
209+
let s = "foobar"
210+
let from = s.startIndex
211+
let to = s.index(before: s.endIndex)
212+
let actual = s[from..<to]
213+
expectEqual("fooba", actual)
214+
}
215+
216+
StringTests.test("String/subscript(_:ClosedRange)") {
217+
let s = "foobar"
218+
let from = s.startIndex
219+
let to = s.index(before: s.endIndex)
220+
let actual = s[from...to]
221+
expectEqual(s, actual)
222+
}
223+
208224
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") {
209225
let donor = "abcdef"
210226
let acceptor = "uvw"

0 commit comments

Comments
 (0)