diff --git a/benchmark/single-source/DropFirst.swift b/benchmark/single-source/DropFirst.swift index a717bc917ec86..c6f2edbee47e3 100644 --- a/benchmark/single-source/DropFirst.swift +++ b/benchmark/single-source/DropFirst.swift @@ -88,7 +88,7 @@ public func run_DropFirstCountableRange(_ N: Int) { let s = 0.. Set { for (left, right) in splits { // drop a character - result.append(left + right.dropFirst()) + result.append(left + right.removingFirst()) // transpose two characters if let fst = right.first { - let drop1 = right.dropFirst() + let drop1 = right.removingFirst() if let snd = drop1.first { - result.append(left + [snd,fst] + drop1.dropFirst()) + result.append(left + [snd,fst] + drop1.removingFirst()) } } // replace each character with another for letter in alphabet { - result.append(left + [letter] + right.dropFirst()) + result.append(left + [letter] + right.removingFirst()) } // insert rogue characters diff --git a/benchmark/single-source/StringMatch.swift b/benchmark/single-source/StringMatch.swift index be300227745d6..afcb4c8b4d063 100644 --- a/benchmark/single-source/StringMatch.swift +++ b/benchmark/single-source/StringMatch.swift @@ -24,7 +24,7 @@ public let StringMatch = BenchmarkInfo( extension String { @inline(__always) - func dropFirst(_ n: Int = 1) -> String { + func removingPrefix(_ n: Int = 1) -> String { let startIndex = self.index(self.startIndex, offsetBy: n) return self[startIndex ..< self.endIndex] } @@ -33,7 +33,7 @@ extension String { /* match: search for regexp anywhere in text */ func match(regexp: String, text: String) -> Bool { if regexp.first == "^" { - return matchHere(regexp.dropFirst(), text) + return matchHere(regexp.removingFirst(), text) } var idx = text.startIndex @@ -55,16 +55,16 @@ func matchHere(_ regexp: String, _ text: String) -> Bool { return true } - if let c = regexp.first, regexp.dropFirst().first == "*" { - return matchStar(c, regexp.dropFirst(2), text) + if let c = regexp.first, regexp.removingFirst().first == "*" { + return matchStar(c, regexp.removingPrefix(2), text) } - if regexp.first == "$" && regexp.dropFirst().isEmpty { + if regexp.first == "$" && regexp.removingFirst().isEmpty { return text.isEmpty } if let tc = text.first, let rc = regexp.first, rc == "." || tc == rc { - return matchHere(regexp.dropFirst(), text.dropFirst()) + return matchHere(regexp.removingFirst(), text.removingFirst()) } return false diff --git a/benchmark/single-source/Substring.swift b/benchmark/single-source/Substring.swift index e3a666193a8ab..395dc81caa3cb 100644 --- a/benchmark/single-source/Substring.swift +++ b/benchmark/single-source/Substring.swift @@ -81,7 +81,7 @@ private func equivalentWithDistinctBuffers() -> (String, Substring) { s0 += "!" // These two should be equal but with distinct buffers, both refcounted. - let a = Substring(s0).dropFirst() + let a = Substring(s0).removingFirst() let b = String(a) return (b, a) } diff --git a/benchmark/utils/ArgParse.swift b/benchmark/utils/ArgParse.swift index 396c01be44041..a532ce63d1c66 100644 --- a/benchmark/utils/ArgParse.swift +++ b/benchmark/utils/ArgParse.swift @@ -46,7 +46,7 @@ public func parseArgs(_ validOptions: [String]? = nil) for arg in CommandLine.arguments[1...self, &result) @@ -847,12 +847,12 @@ extension TestSuite { } } - self.test("\(testNamePrefix).index(where:)/semantics") { + self.test("\(testNamePrefix).firstIndex(where:)/semantics") { for test in findTests { let closureLifetimeTracker = LifetimeTracked(0) expectEqual(1, LifetimeTracked.instances) let c = makeWrappedCollectionWithEquatableElement(test.sequence) - let result = c.index { + let result = c.firstIndex { (candidate) in _blackHole(closureLifetimeTracker) return @@ -903,13 +903,13 @@ extension TestSuite { } //===------------------------------------------------------------------===// - // dropFirst() + // removingPrefix() //===------------------------------------------------------------------===// - self.test("\(testNamePrefix).dropFirst/semantics") { - for test in dropFirstTests { + self.test("\(testNamePrefix).removingPrefix/semantics") { + for test in removingPrefixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) - let result = s.dropFirst(test.dropElements) + let result = s.removingPrefix(test.dropElements) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) @@ -917,13 +917,13 @@ extension TestSuite { } //===------------------------------------------------------------------===// - // dropLast() + // removingSuffix() //===------------------------------------------------------------------===// - self.test("\(testNamePrefix).dropLast/semantics") { - for test in dropLastTests { + self.test("\(testNamePrefix).removingSuffix/semantics") { + for test in removingSuffixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) - let result = s.dropLast(test.dropElements) + let result = s.removingSuffix(test.dropElements) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) @@ -1032,7 +1032,7 @@ extension TestSuite { //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/slice/semantics") { - for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { + for test in removePrefixTests.filter({ $0.numberToRemove == 1 }) { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) var slice = c[...] let survivingIndices = _allIndices( @@ -1068,11 +1068,11 @@ extension TestSuite { } //===------------------------------------------------------------------===// - // removeFirst(n: Int)/slice + // removePrefix(n: Int)/slice //===------------------------------------------------------------------===// - self.test("\(testNamePrefix).removeFirst(n: Int)/slice/semantics") { - for test in removeFirstTests { + self.test("\(testNamePrefix).removePrefix(n: Int)/slice/semantics") { + for test in removePrefixTests { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) var slice = c[...] let survivingIndices = _allIndices( @@ -1081,48 +1081,48 @@ extension TestSuite { slice.startIndex, offsetBy: numericCast(test.numberToRemove)) ..< slice.endIndex ) - slice.removeFirst(test.numberToRemove) + slice.removePrefix(test.numberToRemove) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, - "removeFirst() shouldn't mutate the tail of the slice", + "removePrefix(_:) shouldn't mutate the tail of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, - "removeFirst() shouldn't invalidate indices", + "removePrefix(_:) shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection, c.map { extractValue($0).value }, - "removeFirst() shouldn't mutate the collection that was sliced", + "removePrefix(_:) shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } - self.test("\(testNamePrefix).removeFirst(n: Int)/slice/empty/semantics") { + self.test("\(testNamePrefix).removePrefix(n: Int)/slice/empty/semantics") { let c = makeWrappedCollection(Array>()) var slice = c[c.startIndex..>()) var slice = c[c.startIndex..] let numberToRemove: Int let expectedCollection: [Int] @@ -155,7 +155,7 @@ internal struct RemoveLastNTest { self.collection = collection.map(OpaqueValue.init) self.numberToRemove = numberToRemove self.expectedCollection = expectedCollection - self.loc = SourceLoc(file, line, comment: "removeLast(n: Int) test data") + self.loc = SourceLoc(file, line, comment: "removeSuffix(n: Int) test data") } } @@ -223,43 +223,43 @@ internal struct OperatorPlusTest { } } -let removeLastTests: [RemoveLastNTest] = [ - RemoveLastNTest( +let removeSuffixTests: [RemoveSuffixTest] = [ + RemoveSuffixTest( collection: [1010], numberToRemove: 0, expectedCollection: [1010] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010], numberToRemove: 1, expectedCollection: [] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 0, expectedCollection: [1010, 2020, 3030, 4040, 5050] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 1, expectedCollection: [1010, 2020, 3030, 4040] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 2, expectedCollection: [1010, 2020, 3030] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 3, expectedCollection: [1010, 2020] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 4, expectedCollection: [1010] ), - RemoveLastNTest( + RemoveSuffixTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 5, expectedCollection: [] @@ -798,7 +798,7 @@ self.test("\(testNamePrefix).remove(at:)/semantics") { //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/semantics") { - for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { + for test in removePrefixTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let removedElement = c.removeFirst() expectEqual(test.collection.first, extractValue(removedElement).value) @@ -817,13 +817,13 @@ self.test("\(testNamePrefix).removeFirst()/empty/semantics") { } //===----------------------------------------------------------------------===// -// removeFirst(n: Int) +// removePrefix(n: Int) //===----------------------------------------------------------------------===// -self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") { - for test in removeFirstTests { +self.test("\(testNamePrefix).removePrefix(n: Int)/semantics") { + for test in removePrefixTests { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) - c.removeFirst(test.numberToRemove) + c.removePrefix(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, @@ -833,22 +833,22 @@ self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") { } } -self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") { +self.test("\(testNamePrefix).removePrefix(n: Int)/empty/semantics") { var c = makeWrappedCollection(Array>()) expectCrashLater() - c.removeFirst(1) // Should trap. + c.removePrefix(1) // Should trap. } -self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") { +self.test("\(testNamePrefix).removePrefix(n: Int)/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() - c.removeFirst(-1) // Should trap. + c.removePrefix(-1) // Should trap. } -self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") { +self.test("\(testNamePrefix).removePrefix(n: Int)/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() - c.removeFirst(5) // Should trap. + c.removePrefix(5) // Should trap. } //===----------------------------------------------------------------------===// @@ -1222,7 +1222,7 @@ self.test("\(testNamePrefix).OperatorPlus") { //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/semantics") { - for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { + for test in removeSuffixTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection) let removedElement = c.removeLast() expectEqual( @@ -1244,37 +1244,37 @@ self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/empty/semant } //===----------------------------------------------------------------------===// -// removeLast(n: Int) +// removeSuffix(n: Int) //===----------------------------------------------------------------------===// -self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/semantics") { - for test in removeLastTests { +self.test("\(testNamePrefix).removeSuffix(n: Int)/whereIndexIsBidirectional/semantics") { + for test in removeSuffixTests { var c = makeWrappedCollection(test.collection) - c.removeLast(test.numberToRemove) + c.removeSuffix(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, - "removeLast() shouldn't mutate the head of the collection", + "removeSuffix(_:) shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc)) } } -self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/empty/semantics") { +self.test("\(testNamePrefix).removeSuffix(n: Int)/whereIndexIsBidirectional/empty/semantics") { var c = makeWrappedCollection([]) expectCrashLater() - c.removeLast(1) // Should trap. + c.removeSuffix(1) // Should trap. } -self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeNegative/semantics") { +self.test("\(testNamePrefix).removeSuffix(n: Int)/whereIndexIsBidirectional/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeLast(-1) // Should trap. + c.removeSuffix(-1) // Should trap. } -self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeTooMany/semantics") { +self.test("\(testNamePrefix).removeSuffix(n: Int)/whereIndexIsBidirectional/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeLast(3) // Should trap. + c.removeSuffix(3) // Should trap. } //===----------------------------------------------------------------------===// diff --git a/stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableSliceType.swift b/stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableSliceType.swift index 28a802ee73e14..392b9f56eae71 100644 --- a/stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableSliceType.swift +++ b/stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableSliceType.swift @@ -69,7 +69,7 @@ extension TestSuite { //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/semantics") { - for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { + for test in removePrefixTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let survivingIndices = _allIndices( into: c, @@ -98,49 +98,49 @@ extension TestSuite { } //===----------------------------------------------------------------------===// - // removeFirst(n: Int) + // removePrefix(n: Int) //===----------------------------------------------------------------------===// - self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") { - for test in removeFirstTests { + self.test("\(testNamePrefix).removePrefix(n: Int)/semantics") { + for test in removePrefixTests { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let survivingIndices = _allIndices( into: c, in: c.index(c.startIndex, offsetBy: numericCast(test.numberToRemove)) ..< c.endIndex ) - c.removeFirst(test.numberToRemove) + c.removePrefix(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, - "removeFirst() shouldn't mutate the tail of the collection", + "removePrefix(_:) shouldn't mutate the tail of the collection", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(c[$0]).value }, - "removeFirst() shouldn't invalidate indices", + "removePrefix(_:) shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) } } - self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") { + self.test("\(testNamePrefix).removePrefix(n: Int)/empty/semantics") { var c = makeWrappedCollection(Array>()) expectCrashLater() - c.removeFirst(1) // Should trap. + c.removePrefix(1) // Should trap. } - self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") { + self.test("\(testNamePrefix).removePrefix(n: Int)/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeFirst(-1) // Should trap. + c.removePrefix(-1) // Should trap. } - self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") { + self.test("\(testNamePrefix).removePrefix(n: Int)/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeFirst(3) // Should trap. + c.removePrefix(3) // Should trap. } //===----------------------------------------------------------------------===// @@ -211,7 +211,7 @@ extension TestSuite { //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast()/semantics") { - for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { + for test in removeSuffixTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection) let survivingIndices = _allIndices( into: c, @@ -242,49 +242,49 @@ extension TestSuite { } //===----------------------------------------------------------------------===// - // removeLast(n: Int) + // removeSuffix(n: Int) //===----------------------------------------------------------------------===// - self.test("\(testNamePrefix).removeLast(n: Int)/semantics") { - for test in removeLastTests { + self.test("\(testNamePrefix).removeSuffix(n: Int)/semantics") { + for test in removeSuffixTests { var c = makeWrappedCollection(test.collection) let survivingIndices = _allIndices( into: c, in: c.startIndex ..< c.index(c.endIndex, offsetBy: numericCast(-test.numberToRemove)) ) - c.removeLast(test.numberToRemove) + c.removeSuffix(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, - "removeLast() shouldn't mutate the head of the collection", + "removeSuffix(_:) shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(c[$0]).value }, - "removeLast() shouldn't invalidate indices", + "removeSuffix(_:) shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) } } - self.test("\(testNamePrefix).removeLast(n: Int)/empty/semantics") { + self.test("\(testNamePrefix).removeSuffix(n: Int)/empty/semantics") { var c = makeWrappedCollection(Array>()) expectCrashLater() - c.removeLast(1) // Should trap. + c.removeSuffix(1) // Should trap. } - self.test("\(testNamePrefix).removeLast(n: Int)/removeNegative/semantics") { + self.test("\(testNamePrefix).removeSuffix(n: Int)/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeLast(-1) // Should trap. + c.removeSuffix(-1) // Should trap. } - self.test("\(testNamePrefix).removeLast(n: Int)/removeTooMany/semantics") { + self.test("\(testNamePrefix).removeSuffix(n: Int)/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() - c.removeLast(3) // Should trap. + c.removeSuffix(3) // Should trap. } //===----------------------------------------------------------------------===// diff --git a/stdlib/private/StdlibCollectionUnittest/CheckSequenceType.swift b/stdlib/private/StdlibCollectionUnittest/CheckSequenceType.swift index 721cba0a6a974..aba453e14a1e7 100644 --- a/stdlib/private/StdlibCollectionUnittest/CheckSequenceType.swift +++ b/stdlib/private/StdlibCollectionUnittest/CheckSequenceType.swift @@ -17,7 +17,7 @@ internal enum TestError : Error { case error2 } -public struct DropFirstTest { +public struct RemovingPrefixTest { public var sequence: [Int] public let dropElements: Int public let expected: [Int] @@ -28,11 +28,11 @@ public struct DropFirstTest { self.sequence = sequence self.dropElements = dropElements self.expected = expected - self.loc = SourceLoc(file, line, comment: "dropFirst() test data") + self.loc = SourceLoc(file, line, comment: "removingPrefix() test data") } } -public struct DropLastTest { +public struct RemovingSuffixTest { public var sequence: [Int] public let dropElements: Int public let expected: [Int] @@ -43,7 +43,7 @@ public struct DropLastTest { self.sequence = sequence self.dropElements = dropElements self.expected = expected - self.loc = SourceLoc(file, line, comment: "dropLast() test data") + self.loc = SourceLoc(file, line, comment: "removingSuffix() test data") } } @@ -389,7 +389,7 @@ public struct SplitTest { } } -public struct StartsWithTest { +public struct HasPrefixTest { public let expected: Bool public let sequence: [Int] public let prefix: [Int] @@ -680,66 +680,66 @@ public let flatMapToOptionalTests = [ ] -public let dropFirstTests = [ - DropFirstTest( +public let removingPrefixTests = [ + RemovingPrefixTest( sequence: [], dropElements: 0, expected: [] ), - DropFirstTest( + RemovingPrefixTest( sequence: [1010, 2020, 3030], dropElements: 1, expected: [2020, 3030] ), - DropFirstTest( + RemovingPrefixTest( sequence: [1010, 2020, 3030], dropElements: 2, expected: [3030] ), - DropFirstTest( + RemovingPrefixTest( sequence: [1010, 2020, 3030], dropElements: 3, expected: [] ), - DropFirstTest( + RemovingPrefixTest( sequence: [1010, 2020, 3030], dropElements: 777, expected: [] ), - DropFirstTest( + RemovingPrefixTest( sequence: [1010, 2020, 3030], dropElements: 0, expected: [1010, 2020, 3030] ), ] -public let dropLastTests = [ - DropLastTest( +public let removingSuffixTests = [ + RemovingSuffixTest( sequence: [], dropElements: 0, expected: [] ), - DropLastTest( + RemovingSuffixTest( sequence: [1010, 2020, 3030], dropElements: 1, expected: [1010, 2020] ), - DropLastTest( + RemovingSuffixTest( sequence: [1010, 2020, 3030], dropElements: 2, expected: [1010] ), - DropLastTest( + RemovingSuffixTest( sequence: [1010, 2020, 3030], dropElements: 3, expected: [] ), - DropLastTest( + RemovingSuffixTest( sequence: [1010, 2020, 3030], dropElements: 777, expected: [] ), - DropLastTest( + RemovingSuffixTest( sequence: [1010, 2020, 3030], dropElements: 0, expected: [1010, 2020, 3030] @@ -1410,30 +1410,30 @@ public let prefixTests = [ ), ] -public let startsWithTests = [ +public let hasPrefixTests = [ // Corner cases. - StartsWithTest(true, [], [], [], []), + HasPrefixTest(true, [], [], [], []), - StartsWithTest(false, [], [ 1 ], [], []), - StartsWithTest(true, [ 1 ], [], [], []), + HasPrefixTest(false, [], [ 1 ], [], []), + HasPrefixTest(true, [ 1 ], [], [], []), // Equal sequences. - StartsWithTest(true, [ 1 ], [ 1 ], [], []), - StartsWithTest(true, [ 1, 2 ], [ 1, 2 ], [], []), + HasPrefixTest(true, [ 1 ], [ 1 ], [], []), + HasPrefixTest(true, [ 1, 2 ], [ 1, 2 ], [], []), // Proper prefix. - StartsWithTest(true, [ 0, 1, 2 ], [ 0, 1 ], [], []), - StartsWithTest(false, [ 0, 1 ], [ 0, 1, 2 ], [], []), + HasPrefixTest(true, [ 0, 1, 2 ], [ 0, 1 ], [], []), + HasPrefixTest(false, [ 0, 1 ], [ 0, 1, 2 ], [], []), - StartsWithTest(true, [ 1, 2, 3, 4 ], [ 1, 2 ], [ 4 ], []), - StartsWithTest(false, [ 1, 2 ], [ 1, 2, 3, 4 ], [], [ 4 ]), + HasPrefixTest(true, [ 1, 2, 3, 4 ], [ 1, 2 ], [ 4 ], []), + HasPrefixTest(false, [ 1, 2 ], [ 1, 2, 3, 4 ], [], [ 4 ]), // Not a prefix. - StartsWithTest(false, [ 1, 2, 3, 4 ], [ 1, 2, 10 ], [ 4 ], []), - StartsWithTest(false, [ 1, 2, 10 ], [ 1, 2, 3, 4 ], [], [ 4 ]), + HasPrefixTest(false, [ 1, 2, 3, 4 ], [ 1, 2, 10 ], [ 4 ], []), + HasPrefixTest(false, [ 1, 2, 10 ], [ 1, 2, 3, 4 ], [], [ 4 ]), - StartsWithTest(false, [ 1, 2, 3, 4, 10 ], [ 1, 2, 10 ], [ 4, 10 ], []), - StartsWithTest(false, [ 1, 2, 10 ], [ 1, 2, 3, 4, 10 ], [], [ 4, 10 ]), + HasPrefixTest(false, [ 1, 2, 3, 4, 10 ], [ 1, 2, 10 ], [ 4, 10 ], []), + HasPrefixTest(false, [ 1, 2, 10 ], [ 1, 2, 3, 4, 10 ], [], [ 4, 10 ]), ] @@ -1592,28 +1592,28 @@ self.test("\(testNamePrefix).contains()/WhereElementIsEquatable/semantics") { } //===----------------------------------------------------------------------===// -// dropFirst() +// removingPrefix() //===----------------------------------------------------------------------===// -self.test("\(testNamePrefix).dropFirst/semantics") { - for test in dropFirstTests { +self.test("\(testNamePrefix).removingPrefix/semantics") { + for test in removingPrefixTests { let s = makeWrappedSequence(test.sequence.map(OpaqueValue.init)) - let result = s.dropFirst(test.dropElements) + let result = s.removingPrefix(test.dropElements) expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } -self.test("\(testNamePrefix).dropFirst/semantics/equivalence") { - // Calling dropFirst(1) twice on a sequence should be the same as - // calling dropFirst(2) once on an equivalent sequence. +self.test("\(testNamePrefix).removingPrefix/semantics/equivalence") { + // Calling removingPrefix(1) twice on a sequence should be the same as + // calling removingPrefix(2) once on an equivalent sequence. if true { let s1 = makeWrappedSequence([1010, 2020, 3030, 4040].map(OpaqueValue.init)) let s2 = makeWrappedSequence([1010, 2020, 3030, 4040].map(OpaqueValue.init)) - let result0 = s1.dropFirst(1) - let result1 = result0.dropFirst(1) - let result2 = s2.dropFirst(2) + let result0 = s1.removingPrefix(1) + let result1 = result0.removingPrefix(1) + let result2 = s2.removingPrefix(2) expectEqualSequence( result1.map { extractValue($0).value }, @@ -1622,12 +1622,12 @@ self.test("\(testNamePrefix).dropFirst/semantics/equivalence") { } } -self.test("\(testNamePrefix).dropFirst/semantics/dropFirst()==dropFirst(1)") { +self.test("\(testNamePrefix).removingPrefix/semantics/removingFirst()==removingPrefix(1)") { let s1 = makeWrappedSequence([1010, 2020, 3030].map(OpaqueValue.init)) let s2 = makeWrappedSequence([1010, 2020, 3030].map(OpaqueValue.init)) - let result1 = s1.dropFirst() - let result2 = s2.dropFirst(1) + let result1 = s1.removingFirst() + let result2 = s2.removingPrefix(1) expectEqualSequence( result1.map { extractValue($0).value }, @@ -1635,44 +1635,44 @@ self.test("\(testNamePrefix).dropFirst/semantics/dropFirst()==dropFirst(1)") { ) } -self.test("\(testNamePrefix).dropFirst/semantics/negative") { +self.test("\(testNamePrefix).removingPrefix/semantics/negative") { let s = makeWrappedSequence([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() - _ = s.dropFirst(-1) + _ = s.removingPrefix(-1) } //===----------------------------------------------------------------------===// -// dropLast() +// removingSuffix() //===----------------------------------------------------------------------===// -self.test("\(testNamePrefix).dropLast/semantics") { - for test in dropLastTests { +self.test("\(testNamePrefix).removingSuffix/semantics") { + for test in removingSuffixTests { let s = makeWrappedSequence(test.sequence.map(OpaqueValue.init)) - let result = s.dropLast(test.dropElements) + let result = s.removingSuffix(test.dropElements) expectEqualSequence(test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } -self.test("\(testNamePrefix).dropLast/semantics/equivalence") { - // Calling `dropLast(2)` twice on a sequence is equivalent to calling - // `dropLast(4)` once. +self.test("\(testNamePrefix).removingSuffix/semantics/equivalence") { + // Calling `removingSuffix(2)` twice on a sequence is equivalent to calling + // `removingSuffix(4)` once. if true { let s1 = makeWrappedSequence( [1010, 2020, 3030, 4040, 5050].map(OpaqueValue.init)) let s2 = makeWrappedSequence( [1010, 2020, 3030, 4040, 5050].map(OpaqueValue.init)) - let droppedOnce = s1.dropLast(4) + let droppedOnce = s1.removingSuffix(4) // FIXME: this line should read: // - // let droppedTwice_ = s2.dropLast(2).dropLast(2) + // let droppedTwice_ = s2.removingSuffix(2).removingSuffix(2) // // We can change it when we have real default implementations in protocols // that don't affect regular name lookup. - let droppedTwice_ = s2.dropLast(2) - let droppedTwice = droppedTwice_.dropLast(2) + let droppedTwice_ = s2.removingSuffix(2) + let droppedTwice = droppedTwice_.removingSuffix(2) expectEqualSequence(droppedOnce, droppedTwice) { extractValue($0).value == extractValue($1).value @@ -1680,21 +1680,21 @@ self.test("\(testNamePrefix).dropLast/semantics/equivalence") { } } -self.test("\(testNamePrefix).dropLast/semantics/negative") { +self.test("\(testNamePrefix).removingSuffix/semantics/negative") { let s = makeWrappedSequence([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() - _ = s.dropLast(-1) + _ = s.removingSuffix(-1) } //===----------------------------------------------------------------------===// -// drop(while:) +// removingPrefix(while:) //===----------------------------------------------------------------------===// -self.test("\(testNamePrefix).drop(while:)/semantics").forEach(in: findTests) { +self.test("\(testNamePrefix).removingPrefix(while:)/semantics").forEach(in: findTests) { test in let s = makeWrappedSequenceWithEquatableElement(test.sequence) let closureLifetimeTracker = LifetimeTracked(0) - let remainingSequence = s.drop { + let remainingSequence = s.removingPrefix { _blackHole(closureLifetimeTracker) return $0 != wrapValueIntoEquatable(test.element) } diff --git a/stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift.gyb b/stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift.gyb index 32ff5ce50e591..cf77a0708cd47 100644 --- a/stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift.gyb +++ b/stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift.gyb @@ -82,9 +82,9 @@ public class SequenceLog { public static var map = TypeIndexed(0) public static var filter = TypeIndexed(0) public static var forEach = TypeIndexed(0) - public static var dropFirst = TypeIndexed(0) - public static var dropLast = TypeIndexed(0) - public static var dropWhile = TypeIndexed(0) + public static var removingPrefix = TypeIndexed(0) + public static var removingSuffix = TypeIndexed(0) + public static var removingPrefixWhile = TypeIndexed(0) public static var prefixWhile = TypeIndexed(0) public static var prefixMaxLength = TypeIndexed(0) public static var suffixMaxLength = TypeIndexed(0) @@ -248,21 +248,21 @@ public struct ${Self}< public typealias SubSequence = Base.SubSequence - public func dropFirst(_ n: Int) -> SubSequence { - Log.dropFirst[selfType] += 1 - return base.dropFirst(n) + public func removingPrefix(_ n: Int) -> SubSequence { + Log.removingPrefix[selfType] += 1 + return base.removingPrefix(n) } - public func dropLast(_ n: Int) -> SubSequence { - Log.dropLast[selfType] += 1 - return base.dropLast(n) + public func removingSuffix(_ n: Int) -> SubSequence { + Log.removingSuffix[selfType] += 1 + return base.removingSuffix(n) } - public func drop( + public func removingPrefix( while predicate: (Base.Iterator.Element) throws -> Bool ) rethrows -> SubSequence { - Log.dropWhile[selfType] += 1 - return try base.drop(while: predicate) + Log.removingPrefixWhile[selfType] += 1 + return try base.removingPrefix(while: predicate) } public func prefix(_ maxLength: Int) -> SubSequence { @@ -493,9 +493,9 @@ public struct ${Self}< return base._customRemoveLast() } - public mutating func _customRemoveLast(_ n: Int) -> Bool { + public mutating func _customRemoveSuffix(_ n: Int) -> Bool { Log._customRemoveLastN[selfType] += 1 - return base._customRemoveLast(n) + return base._customRemoveSuffix(n) } public mutating func append(_ newElement: Base.Iterator.Element) { @@ -541,9 +541,9 @@ public struct ${Self}< return base.removeFirst() } - public mutating func removeFirst(_ n: Int) { + public mutating func removePrefix(_ n: Int) { Log.removeFirstN[selfType] += 1 - base.removeFirst(n) + base.removePrefix(n) } public mutating func removeSubrange(_ bounds: Range) { diff --git a/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb b/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb index 96968b3e47868..420105ca24177 100644 --- a/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb +++ b/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb @@ -343,7 +343,7 @@ internal struct _CollectionStateTransition { transitions = Box<[_CollectionStateTransition]>([]) _CollectionStateTransition._allTransitions[previousState] = transitions } - if let i = transitions!.value.index(where: { $0._operation == operation }) { + if let i = transitions!.value.firstIndex(where: { $0._operation == operation }) { self = transitions!.value[i] return } diff --git a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb index 2c849627fe070..df1604332761b 100644 --- a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb +++ b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb @@ -99,7 +99,7 @@ public struct SourceLocStack { public func print() { let top = locs.first! Swift.print("check failed at \(top.file), line \(top.line)") - _printStackTrace(SourceLocStack(_locs: Array(locs.dropFirst()))) + _printStackTrace(SourceLocStack(_locs: Array(locs.removingFirst()))) } } diff --git a/stdlib/private/SwiftPrivate/IO.swift b/stdlib/private/SwiftPrivate/IO.swift index 4a4ca2b9022ca..0c15b996dba12 100644 --- a/stdlib/private/SwiftPrivate/IO.swift +++ b/stdlib/private/SwiftPrivate/IO.swift @@ -25,7 +25,7 @@ public struct _FDInputStream { public mutating func getline() -> String? { if let newlineIndex = - _buffer[0..<_bufferUsed].index(of: UInt8(Unicode.Scalar("\n").value)) { + _buffer[0..<_bufferUsed].firstIndex(of: UInt8(Unicode.Scalar("\n").value)) { let result = String._fromWellFormedCodeUnitSequence( UTF8.self, input: _buffer[0.. Storage { + func removingLast() -> Storage { switch self { case .empty: return .empty @@ -65,7 +65,7 @@ public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableColl case 3: return .pair(indexes[0], indexes[1]) default: - return .array(Array(indexes.dropLast())) + return .array(Array(indexes.removingLast())) } } } @@ -563,8 +563,8 @@ public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableColl } /// Return a new `IndexPath` containing all but the last element. - public func dropLast() -> IndexPath { - return IndexPath(storage: _indexes.dropLast()) + public func removingLast() -> IndexPath { + return IndexPath(storage: _indexes.removingLast()) } /// Append an `IndexPath` to `self`. diff --git a/stdlib/public/core/Arrays.swift.gyb b/stdlib/public/core/Arrays.swift.gyb index 773e7fb27070d..0b532cc407cdd 100644 --- a/stdlib/public/core/Arrays.swift.gyb +++ b/stdlib/public/core/Arrays.swift.gyb @@ -137,11 +137,11 @@ if True: /// tasked with finding the first two days with absences in the session. To /// find the indices of the two days in question, follow these steps: /// -/// 1) Call `index(where:)` to find the index of the first element in the +/// 1) Call `firstIndex(where:)` to find the index of the first element in the /// `absences` array that is greater than zero. /// 2) Create a slice of the `absences` array starting after the index found in /// step 1. -/// 3) Call `index(where:)` again, this time on the slice created in step 2. +/// 3) Call `firstIndex(where:)` again, this time on the slice created in step 2. /// Where in some languages you might pass a starting index into an /// `indexOf` method to find the second day, in Swift you perform the same /// operation on a slice of the original array. @@ -150,9 +150,9 @@ if True: /// /// Here's an implementation of those steps: /// -/// if let i = absences.index(where: { $0 > 0 }) { // 1 +/// if let i = absences.firstIndex(where: { $0 > 0 }) { // 1 /// let absencesAfterFirst = absences[(i + 1)...] // 2 -/// if let j = absencesAfterFirst.index(where: { $0 > 0 }) { // 3 +/// if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3 /// print("The first day with absences had \(absences[i]).") // 4 /// print("The second day with absences had \(absences[j]).") /// } @@ -293,7 +293,7 @@ if True: /// You can replace an existing element with a new value by assigning the new /// value to the subscript. /// -/// if let i = students.index(of: "Maxime") { +/// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// // ["Ivy", "Jordell", "Liam", "Max", "Shakia"] @@ -492,7 +492,7 @@ public struct ${Self} /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] - /// if let i = numbers.index(of: 30) { + /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" @@ -727,7 +727,7 @@ public struct ${Self} /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let i = streetsSlice.index(of: "Evarts") // 4 + /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift index 5abd3eb53a88d..700603e7ed41d 100644 --- a/stdlib/public/core/BidirectionalCollection.swift +++ b/stdlib/public/core/BidirectionalCollection.swift @@ -123,7 +123,7 @@ public protocol BidirectionalCollection : Collection /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// @@ -257,7 +257,7 @@ extension BidirectionalCollection where SubSequence == Self { /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable // FIXME(sil-serialize-all) - public mutating func removeLast(_ n: Int) { + public mutating func removeSuffix(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), @@ -274,9 +274,9 @@ extension BidirectionalCollection { /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropLast(2)) + /// print(numbers.removingSuffix(2)) /// // Prints "[1, 2, 3]" - /// print(numbers.dropLast(10)) + /// print(numbers.removingSuffix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the @@ -285,7 +285,7 @@ extension BidirectionalCollection { /// /// - Complexity: O(*n*), where *n* is the number of elements to drop. @_inlineable // FIXME(sil-serialize-all) - public func dropLast(_ n: Int) -> SubSequence { + public func removingSuffix(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let end = index( @@ -294,7 +294,7 @@ extension BidirectionalCollection { limitedBy: startIndex) ?? startIndex return self[startIndex.. { /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// @@ -1170,7 +1170,7 @@ extension Collection { } // TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)? - /// Customization point for `Collection.index(of:)`. + /// Customization point for `Collection.firstIndex(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. @@ -1240,9 +1240,9 @@ extension Collection { /// the collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropFirst(2)) + /// print(numbers.removingPrefix(2)) /// // Prints "[3, 4, 5]" - /// print(numbers.dropFirst(10)) + /// print(numbers.removingPrefix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of @@ -1253,13 +1253,13 @@ extension Collection { /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the collection. @_inlineable - public func dropFirst(_ n: Int) -> SubSequence { + public func removingPrefix(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = index(startIndex, offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex return self[start.. SubSequence { + public func removingSuffix(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, numericCast(count) - n) @@ -1298,7 +1298,7 @@ extension Collection { /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable - public func drop( + public func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { var start = startIndex @@ -1307,7 +1307,7 @@ extension Collection { } return self[start..= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), @@ -1705,3 +1705,13 @@ extension Collection { @available(swift, deprecated: 3.2, renamed: "Element") public typealias _Element = Element } + +// Compatibility aliases for Swift 4 names (see SE-0132) + +extension Collection where SubSequence == Self { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removePrefix(_:)") + @_inlineable + public mutating func removeFirst(_ n: Int) { + return removePrefix(n) + } +} diff --git a/stdlib/public/core/CollectionAlgorithms.swift.gyb b/stdlib/public/core/CollectionAlgorithms.swift.gyb index 7c78c5a677007..c2d0790557369 100644 --- a/stdlib/public/core/CollectionAlgorithms.swift.gyb +++ b/stdlib/public/core/CollectionAlgorithms.swift.gyb @@ -31,20 +31,20 @@ extension BidirectionalCollection { } //===----------------------------------------------------------------------===// -// index(of:)/index(where:) +// firstIndex(of:)/firstIndex(where:) //===----------------------------------------------------------------------===// extension Collection where Element : Equatable { /// Returns the first index where the specified value appears in the /// collection. /// - /// After using `index(of:)` to find the position of a particular element in + /// After using `firstIndex(of:)` to find the position of a particular element in /// a collection, you can use it to access the element by subscripting. This /// example shows how you can modify one of the names in an array of /// students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] - /// if let i = students.index(of: "Maxime") { + /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) @@ -54,7 +54,7 @@ extension Collection where Element : Equatable { /// - Returns: The first index where `element` is found. If `element` is not /// found in the collection, returns `nil`. @_inlineable - public func index(of element: Element) -> Index? { + public func firstIndex(of element: Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } @@ -80,7 +80,7 @@ extension Collection { /// begins with the letter "A": /// /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] - /// if let i = students.index(where: { $0.hasPrefix("A") }) { + /// if let i = students.firstIndex(where: { $0.hasPrefix("A") }) { /// print("\(students[i]) starts with 'A'!") /// } /// // Prints "Abena starts with 'A'!" @@ -92,7 +92,7 @@ extension Collection { /// `true`. If no elements in the collection satisfy the given predicate, /// returns `nil`. @_inlineable - public func index( + public func firstIndex( where predicate: (Element) throws -> Bool ) rethrows -> Index? { var i = self.startIndex @@ -451,3 +451,23 @@ ${orderingExplanation} } } } + +// Compatibility aliases for Swift 4 names (see SE-0132) + +extension Collection where Element : Equatable { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "firstIndex(of:)") + @_inlineable + public func index(of element: Element) -> Index? { + return firstIndex(of: element) + } +} + +extension Collection { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "firstIndex(where:)") + @_inlineable + public func index( + where predicate: (Element) throws -> Bool + ) rethrows -> Index? { + return try firstIndex(where: predicate) + } +} diff --git a/stdlib/public/core/DropWhile.swift.gyb b/stdlib/public/core/DropWhile.swift.gyb index 8e8e62530ee8b..1b6e96b0e70a8 100644 --- a/stdlib/public/core/DropWhile.swift.gyb +++ b/stdlib/public/core/DropWhile.swift.gyb @@ -1,4 +1,4 @@ -//===--- DropWhile.swift.gyb - Lazy views for drop(while:) ----*- swift -*-===// +//===--- DropWhile.swift.gyb - Lazy views for removingPrefix(while:) ----*- swift -*-===// // // This source file is part of the Swift.org open source project // @@ -103,7 +103,7 @@ extension LazySequenceProtocol { /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @_inlineable // FIXME(sil-serialize-all) - public func drop( + public func removingPrefix( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileSequence { return LazyDropWhileSequence(_base: self.elements, predicate: predicate) @@ -231,7 +231,7 @@ Elements : ${Collection} /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @_inlineable // FIXME(sil-serialize-all) - public func drop( + public func removingPrefix( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhile${Collection} { return LazyDropWhile${Collection}( diff --git a/stdlib/public/core/ExistentialCollection.swift.gyb b/stdlib/public/core/ExistentialCollection.swift.gyb index 709f167caa035..13f99a34e838a 100644 --- a/stdlib/public/core/ExistentialCollection.swift.gyb +++ b/stdlib/public/core/ExistentialCollection.swift.gyb @@ -266,7 +266,7 @@ internal class _AnyRandomAccessCollectionBox % override = 'override' if Kind != 'Sequence' else '' @_versioned @_inlineable - internal ${override} func _drop( + internal ${override} func _removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> _Any${Kind}Box { _abstract() @@ -274,13 +274,13 @@ internal class _AnyRandomAccessCollectionBox @_versioned @_inlineable - internal ${override} func _dropFirst(_ n: Int) -> _Any${Kind}Box { + internal ${override} func _removingPrefix(_ n: Int) -> _Any${Kind}Box { _abstract() } @_versioned @_inlineable - internal ${override} func _dropLast(_ n: Int) -> _Any${Kind}Box { + internal ${override} func _removingSuffix(_ n: Int) -> _Any${Kind}Box { _abstract() } @@ -512,20 +512,20 @@ internal final class _${Kind}Box : _Any${Kind}Box Bool ) rethrows -> _Any${Kind}Box { - return try _${Kind}Box(_base: _base.drop(while: predicate)) + return try _${Kind}Box(_base: _base.removingPrefix(while: predicate)) } @_versioned @_inlineable - internal override func _dropFirst(_ n: Int) -> _Any${Kind}Box { - return _${Kind}Box(_base: _base.dropFirst(n)) + internal override func _removingPrefix(_ n: Int) -> _Any${Kind}Box { + return _${Kind}Box(_base: _base.removingPrefix(n)) } @_versioned @_inlineable - internal override func _dropLast(_ n: Int) -> _Any${Kind}Box { - return _${Kind}Box(_base: _base.dropLast(n)) + internal override func _removingSuffix(_ n: Int) -> _Any${Kind}Box { + return _${Kind}Box(_base: _base.removingSuffix(n)) } @_versioned @_inlineable @@ -817,20 +817,20 @@ extension Any${Kind} { } @_inlineable - public func drop( + public func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> Any${Kind} { - return try Any${Kind}(_box: _box._drop(while: predicate)) + return try Any${Kind}(_box: _box._removingPrefix(while: predicate)) } @_inlineable - public func dropFirst(_ n: Int) -> Any${Kind} { - return Any${Kind}(_box: _box._dropFirst(n)) + public func removingPrefix(_ n: Int) -> Any${Kind} { + return Any${Kind}(_box: _box._removingPrefix(n)) } @_inlineable - public func dropLast(_ n: Int) -> Any${Kind} { - return Any${Kind}(_box: _box._dropLast(n)) + public func removingSuffix(_ n: Int) -> Any${Kind} { + return Any${Kind}(_box: _box._removingSuffix(n)) } @_inlineable diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb index 36f88c825dc5b..c60485f6dc424 100644 --- a/stdlib/public/core/HashedCollections.swift.gyb +++ b/stdlib/public/core/HashedCollections.swift.gyb @@ -564,10 +564,10 @@ public struct Set : /// - Returns: The index of `member` if it exists in the set; otherwise, /// `nil`. @_inlineable // FIXME(sil-serialize-all) - public func index(of member: Element) -> Index? { + public func firstIndex(of member: Element) -> Index? { return _variantBuffer.index(forKey: member) } - + /// Inserts the given element in the set if it is not already present. /// /// If an element equal to `newMember` is already contained in the set, this @@ -1206,7 +1206,7 @@ public struct Set : public func _customIndexOfEquatableElement( _ member: Element ) -> Index?? { - return Optional(index(of: member)) + return Optional(firstIndex(of: member)) } // @@ -1660,7 +1660,7 @@ public func _setBridgeFromObjectiveCConditional< /// provides, see the `DictionaryLiteral` type for an alternative. /// /// You can search a dictionary's contents for a particular value using the -/// `contains(where:)` or `index(where:)` methods supplied by default +/// `contains(where:)` or `firstIndex(where:)` methods supplied by default /// implementation. The following example checks to see if `imagePaths` contains /// any paths in the `"/glyphs"` directory: /// @@ -1951,10 +1951,10 @@ public struct Dictionary : /// this subscript with the resulting value. /// /// For example, to find the key for a particular value in a dictionary, use - /// the `index(where:)` method. + /// the `firstIndex(where:)` method. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] - /// if let index = countryCodes.index(where: { $0.value == "Japan" }) { + /// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) { /// print(countryCodes[index]) /// print("Japan's country code is '\(countryCodes[index].key)'.") /// } else { @@ -6634,3 +6634,13 @@ extension Set { } } } + +// Compatibility aliases for Swift 4 names (see SE-0132) + +extension Set { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "firstIndex(of:)") + @_inlineable // FIXME(sil-serialize-all) + public func index(of member: Element) -> Index? { + return firstIndex(of: member) + } +} diff --git a/stdlib/public/core/LazyCollection.swift.gyb b/stdlib/public/core/LazyCollection.swift.gyb index 995e357d05fd5..1883c97dbe126 100644 --- a/stdlib/public/core/LazyCollection.swift.gyb +++ b/stdlib/public/core/LazyCollection.swift.gyb @@ -186,7 +186,7 @@ extension ${Self} : ${TraversalCollection} { return _base.count } - // The following requirement enables dispatching for index(of:) when + // The following requirement enables dispatching for firstIndex(of:) when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; diff --git a/stdlib/public/core/Mirror.swift b/stdlib/public/core/Mirror.swift index 92f5b09297384..e0433ccfeab22 100644 --- a/stdlib/public/core/Mirror.swift +++ b/stdlib/public/core/Mirror.swift @@ -446,7 +446,7 @@ extension Mirror { /// i0 != children.endIndex /// { /// let grandChildren = Mirror(reflecting: children[i0].value).children - /// if let i1 = grandChildren.index(where: { $0.label == "two" }) { + /// if let i1 = grandChildren.firstIndex(where: { $0.label == "two" }) { /// let greatGrandChildren = /// Mirror(reflecting: grandChildren[i1].value).children /// if let i2 = greatGrandChildren.index( @@ -811,11 +811,11 @@ public protocol _DefaultCustomPlaygroundQuickLookable { /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to -/// `index(where:)` in the following example must traverse the whole +/// `firstIndex(where:)` in the following example must traverse the whole /// collection to find the element that matches the predicate: /// /// let runner = "Marlies Gohr" -/// if let index = recordTimes.index(where: { $0.0 == runner }) { +/// if let index = recordTimes.firstIndex(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { diff --git a/stdlib/public/core/MutableCollection.swift b/stdlib/public/core/MutableCollection.swift index 15860eccc24fc..f18d9a3850ed9 100644 --- a/stdlib/public/core/MutableCollection.swift +++ b/stdlib/public/core/MutableCollection.swift @@ -25,7 +25,7 @@ public typealias MutableIndexable = MutableCollection /// modify one of the names in an array of students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] -/// if let i = students.index(of: "Maxime") { +/// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) @@ -110,7 +110,7 @@ public protocol MutableCollection : Collection /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" @@ -209,7 +209,7 @@ extension MutableCollection { /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" diff --git a/stdlib/public/core/RandomAccessCollection.swift b/stdlib/public/core/RandomAccessCollection.swift index d3f5f3ab30736..f87c9d061d0d9 100644 --- a/stdlib/public/core/RandomAccessCollection.swift +++ b/stdlib/public/core/RandomAccessCollection.swift @@ -90,7 +90,7 @@ public protocol RandomAccessCollection : BidirectionalCollection /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// @@ -127,7 +127,7 @@ extension RandomAccessCollection where SubSequence == RandomAccessSlice { /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// - /// let index = streetsSlice.index(of: "Evarts") // 4 + /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// diff --git a/stdlib/public/core/Range.swift.gyb b/stdlib/public/core/Range.swift.gyb index d0066b7901cba..7bd4c10df9d71 100644 --- a/stdlib/public/core/Range.swift.gyb +++ b/stdlib/public/core/Range.swift.gyb @@ -970,7 +970,7 @@ public struct PartialRangeFrom: RangeExpression { /// do not use one with methods that read the entire sequence before /// returning, such as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to /// use operations that put an upper limit on the number of elements they -/// access, such as `prefix(_:)` or `dropFirst(_:)`, and operations that you +/// access, such as `prefix(_:)` or `removingPrefix(_:)`, and operations that you /// can guarantee will terminate, such as passing a closure you know will /// eventually return `true` to `first(where:)`. /// @@ -1168,7 +1168,7 @@ extension Strideable where Stride: SignedInteger { /// indefinitely, do not use one with methods such as `map(_:)`, /// `filter(_:)`, or `suffix(_:)` that read the entire sequence before /// returning. It is safe to use operations that put an upper limit on the - /// number of elements they access, such as `prefix(_:)` or `dropFirst(_:)`, + /// number of elements they access, such as `prefix(_:)` or `removingPrefix(_:)`, /// and operations that you can guarantee will terminate, such as passing a /// closure you know will eventually return `true` to `first(where:)`. /// diff --git a/stdlib/public/core/RangeReplaceableCollection.swift.gyb b/stdlib/public/core/RangeReplaceableCollection.swift.gyb index fd539dd456808..f2c66d5edb549 100644 --- a/stdlib/public/core/RangeReplaceableCollection.swift.gyb +++ b/stdlib/public/core/RangeReplaceableCollection.swift.gyb @@ -298,11 +298,11 @@ public protocol RangeReplaceableCollection : Collection /// - Returns: A non-nil value if the operation was performed. mutating func _customRemoveLast() -> Element? - /// Customization point for `removeLast(_:)`. Implement this function if you + /// Customization point for `removeSuffix(_:)`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: `true` if the operation was performed. - mutating func _customRemoveLast(_ n: Int) -> Bool + mutating func _customRemoveSuffix(_ n: Int) -> Bool /// Removes and returns the first element of the collection. /// @@ -326,7 +326,7 @@ public protocol RangeReplaceableCollection : Collection /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] - /// bugs.removeFirst(3) + /// bugs.removePrefix(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// @@ -338,7 +338,7 @@ public protocol RangeReplaceableCollection : Collection /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. - mutating func removeFirst(_ n: Int) + mutating func removePrefix(_ n: Int) /// Removes all elements from the collection. /// @@ -573,7 +573,7 @@ extension RangeReplaceableCollection { /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] - /// bugs.removeFirst(3) + /// bugs.removePrefix(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// @@ -586,7 +586,7 @@ extension RangeReplaceableCollection { /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable - public mutating func removeFirst(_ n: Int) { + public mutating func removePrefix(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), @@ -594,7 +594,7 @@ extension RangeReplaceableCollection { let end = index(startIndex, offsetBy: numericCast(n)) removeSubrange(startIndex..= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), @@ -814,7 +814,7 @@ extension RangeReplaceableCollection { } @_inlineable - public mutating func _customRemoveLast(_ n: Int) -> Bool { + public mutating func _customRemoveSuffix(_ n: Int) -> Bool { return false } } @@ -832,7 +832,7 @@ extension RangeReplaceableCollection } @_inlineable - public mutating func _customRemoveLast(_ n: Int) -> Bool { + public mutating func _customRemoveSuffix(_ n: Int) -> Bool { self = self[startIndex..= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") - if _customRemoveLast(n) { + if _customRemoveSuffix(n) { return } let end = endIndex @@ -933,12 +933,12 @@ extension RangeReplaceableCollection /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @_inlineable - public mutating func removeLast(_ n: Int) { + public mutating func removeSuffix(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") - if _customRemoveLast(n) { + if _customRemoveSuffix(n) { return } let end = endIndex @@ -1082,3 +1082,33 @@ extension RangeReplaceableCollection { return try Self(self.lazy.filter(isIncluded)) } } + +// Compatibility aliases for Swift 4 names (see SE-0132) + +extension RangeReplaceableCollection { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removePrefix(_:)") + @_inlineable + public mutating func removeFirst(_ n: Int) { + removePrefix(n) + } +} + +extension RangeReplaceableCollection where Self : BidirectionalCollection { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removeSuffix(_:)") + @_inlineable + public mutating func removeLast(_ n: Int) { + removeSuffix(n) + } +} + +extension RangeReplaceableCollection + where + Self : BidirectionalCollection, + SubSequence == Self +{ + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removeSuffix(_:)") + @_inlineable + public mutating func removeLast(_ n: Int) { + removeSuffix(n) + } +} diff --git a/stdlib/public/core/Reverse.swift b/stdlib/public/core/Reverse.swift index 98bfd52aecbbb..5a10b82eb362c 100644 --- a/stdlib/public/core/Reverse.swift +++ b/stdlib/public/core/Reverse.swift @@ -87,7 +87,7 @@ public struct ReversedIndex : Comparable { /// `"a"` character in a string's character view. /// /// let name = "Horatio" - /// let aIndex = name.index(of: "a")! + /// let aIndex = name.firstIndex(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() @@ -118,7 +118,7 @@ public struct ReversedIndex : Comparable { /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() - /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) + /// guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) @@ -285,7 +285,7 @@ public struct ReversedRandomAccessIndex< /// index of the `"a"` character in a string's character view. /// /// let name = "Horatio" - /// let aIndex = name.index(of: "a")! + /// let aIndex = name.firstIndex(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() @@ -318,7 +318,7 @@ public struct ReversedRandomAccessIndex< /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() - /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) + /// guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) diff --git a/stdlib/public/core/Sequence.swift b/stdlib/public/core/Sequence.swift index 834b4abd3d8a1..a02b844948951 100644 --- a/stdlib/public/core/Sequence.swift +++ b/stdlib/public/core/Sequence.swift @@ -415,10 +415,10 @@ public protocol Sequence { /// parameter. func forEach(_ body: (Element) throws -> Void) rethrows - // Note: The complexity of Sequence.dropFirst(_:) requirement - // is documented as O(n) because Collection.dropFirst(_:) is + // Note: The complexity of Sequence.removingPrefix(_:) requirement + // is documented as O(n) because Collection.removingPrefix(_:) is // implemented in O(n), even though the default - // implementation for Sequence.dropFirst(_:) is O(1). + // implementation for Sequence.removingPrefix(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// @@ -426,9 +426,9 @@ public protocol Sequence { /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropFirst(2)) + /// print(numbers.removingPrefix(2)) /// // Prints "[3, 4, 5]" - /// print(numbers.dropFirst(10)) + /// print(numbers.removingPrefix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of @@ -438,7 +438,7 @@ public protocol Sequence { /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. - func dropFirst(_ n: Int) -> SubSequence + func removingPrefix(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. @@ -448,9 +448,9 @@ public protocol Sequence { /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropLast(2)) + /// print(numbers.removingSuffix(2)) /// // Prints "[1, 2, 3]" - /// print(numbers.dropLast(10)) + /// print(numbers.removingSuffix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the @@ -458,7 +458,7 @@ public protocol Sequence { /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. - func dropLast(_ n: Int) -> SubSequence + func removingSuffix(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. @@ -468,7 +468,7 @@ public protocol Sequence { /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. - func drop( + func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence @@ -629,7 +629,7 @@ extension Sequence where Self.Iterator == Self { /// The underlying iterator's sequence may be infinite. @_versioned @_fixed_layout -internal struct _DropFirstSequence +internal struct _RemovingPrefixSequence : Sequence, IteratorProtocol { @_versioned @@ -649,7 +649,7 @@ internal struct _DropFirstSequence @_versioned @_inlineable - internal func makeIterator() -> _DropFirstSequence { + internal func makeIterator() -> _RemovingPrefixSequence { return self } @@ -668,14 +668,14 @@ internal struct _DropFirstSequence @_versioned @_inlineable - internal func dropFirst(_ n: Int) -> AnySequence { - // If this is already a _DropFirstSequence, we need to fold in + internal func removingPrefix(_ n: Int) -> AnySequence { + // If this is already a _RemovingPrefixSequence, we need to fold in // the current drop count and drop limit so no data is lost. // - // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to - // [1,2,3,4].dropFirst(2). + // i.e. [1,2,3,4].removingPrefix(1).removingPrefix(1) should be equivalent to + // [1,2,3,4].removingPrefix(2). return AnySequence( - _DropFirstSequence( + _RemovingPrefixSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } @@ -785,7 +785,7 @@ internal struct _DropWhileSequence @_versioned @_inlineable - internal func drop( + internal func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence { // If this is already a _DropWhileSequence, avoid multiple @@ -1193,9 +1193,9 @@ extension Sequence where SubSequence == AnySequence { /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropFirst(2)) + /// print(numbers.removingPrefix(2)) /// // Prints "[3, 4, 5]" - /// print(numbers.dropFirst(10)) + /// print(numbers.removingPrefix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of @@ -1205,12 +1205,12 @@ extension Sequence where SubSequence == AnySequence { /// /// - Complexity: O(1). @_inlineable - public func dropFirst(_ n: Int) -> AnySequence { + public func removingPrefix(_ n: Int) -> AnySequence { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } - return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) + return AnySequence(_RemovingPrefixSequence(_iterator: makeIterator(), limit: n)) } - + /// Returns a subsequence containing all but the given number of final /// elements. /// @@ -1219,9 +1219,9 @@ extension Sequence where SubSequence == AnySequence { /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropLast(2)) + /// print(numbers.removingSuffix(2)) /// // Prints "[1, 2, 3]" - /// print(numbers.dropLast(10)) + /// print(numbers.removingSuffix(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the @@ -1230,7 +1230,7 @@ extension Sequence where SubSequence == AnySequence { /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable - public func dropLast(_ n: Int) -> AnySequence { + public func removingSuffix(_ n: Int) -> AnySequence { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } @@ -1255,17 +1255,17 @@ extension Sequence where SubSequence == AnySequence { } return AnySequence(result) } - + /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// - /// The following example uses the `drop(while:)` method to skip over the + /// The following example uses the `removingPrefix(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] - /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) + /// let startingWithNegative = numbers.removingPrefix(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an @@ -1279,14 +1279,14 @@ extension Sequence where SubSequence == AnySequence { /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable - public func drop( + public func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } - + /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// @@ -1360,13 +1360,13 @@ extension Sequence { /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropFirst()) + /// print(numbers.removingFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] - /// print(empty.dropFirst()) + /// print(empty.removingFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the @@ -1374,28 +1374,28 @@ extension Sequence { /// /// - Complexity: O(1) @_inlineable - public func dropFirst() -> SubSequence { return dropFirst(1) } - + public func removingFirst() -> SubSequence { return removingPrefix(1) } + /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. /// /// let numbers = [1, 2, 3, 4, 5] - /// print(numbers.dropLast()) + /// print(numbers.removingLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] - /// print(empty.dropLast()) + /// print(empty.removingLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable - public func dropLast() -> SubSequence { return dropLast(1) } + public func removingLast() -> SubSequence { return removingSuffix(1) } } extension Sequence { @@ -1457,3 +1457,35 @@ public struct IteratorSequence< @_versioned internal var _base: Base } + +// Compatibility aliases for Swift 4 names (see SE-0132) + +extension Sequence { + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removingPrefix(_:)") + @_inlineable + public func dropFirst(_ n: Int) -> SubSequence { + return removingPrefix(n) + } + + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removingSuffix(_:)") + @_inlineable + public func dropLast(_ n: Int) -> SubSequence { + return removingSuffix(n) + } + + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removingPrefix(while:)") + @_inlineable + public func drop( + while predicate: (Element) throws -> Bool + ) rethrows -> SubSequence { + return try removingPrefix(while: predicate) + } + + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removingFirst()") + @_inlineable + public func dropFirst() -> SubSequence { return removingFirst() } + + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "removingLast()") + @_inlineable + public func dropLast() -> SubSequence { return removingLast() } +} diff --git a/stdlib/public/core/SequenceAlgorithms.swift.gyb b/stdlib/public/core/SequenceAlgorithms.swift.gyb index 1728740360cd2..2dc7e5a34e57e 100644 --- a/stdlib/public/core/SequenceAlgorithms.swift.gyb +++ b/stdlib/public/core/SequenceAlgorithms.swift.gyb @@ -213,7 +213,7 @@ ${orderingExplanation} % end //===----------------------------------------------------------------------===// -// starts(with:) +// hasPrefix(_:) //===----------------------------------------------------------------------===// % # Generate two versions: with explicit predicates and with @@ -246,13 +246,13 @@ ${equivalenceExplanation} /// let a = 1...3 /// let b = 1...10 /// - /// print(b.starts(with: a)) + /// print(b.hasPrefix(a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// - /// print(b.starts(with: [])) + /// print(b.hasPrefix([])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. @@ -261,8 +261,8 @@ ${equivalenceExplanation} /// `possiblePrefix` has no elements, the return value is `true`. % end @_inlineable - public func starts( - with possiblePrefix: PossiblePrefix${"," if preds else ""} + public func hasPrefix( + _ possiblePrefix: PossiblePrefix${"," if preds else ""} % if preds: by areEquivalent: (Element, Element) throws -> Bool % end @@ -284,6 +284,25 @@ ${equivalenceExplanation} } return possiblePrefixIterator.next() == nil } + + // Compatibility alias for Swift 4 name (see SE-0132) + @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "hasPrefix(_:${"by:" if preds else ""})") + @_inlineable + public func starts( + with possiblePrefix: PossiblePrefix${"," if preds else ""} +% if preds: + by areEquivalent: (Element, Element) throws -> Bool +% end + ) ${rethrows_}-> Bool + where + PossiblePrefix : Sequence, + PossiblePrefix.Element == Element { +% if preds: + return try hasPrefix(possiblePrefix, by: areEquivalent) +% else: + return hasPrefix(possiblePrefix) +% end + } } % end diff --git a/stdlib/public/core/SequenceWrapper.swift b/stdlib/public/core/SequenceWrapper.swift index f89c407cfaf12..88e25761ce3ee 100644 --- a/stdlib/public/core/SequenceWrapper.swift +++ b/stdlib/public/core/SequenceWrapper.swift @@ -91,12 +91,12 @@ extension _SequenceWrapper { extension _SequenceWrapper where SubSequence == Base.SubSequence { @_inlineable // FIXME(sil-serialize-all) - public func dropFirst(_ n: Int) -> SubSequence { - return _base.dropFirst(n) + public func removingPrefix(_ n: Int) -> SubSequence { + return _base.removingPrefix(n) } @_inlineable // FIXME(sil-serialize-all) - public func dropLast(_ n: Int) -> SubSequence { - return _base.dropLast(n) + public func removingSuffix(_ n: Int) -> SubSequence { + return _base.removingSuffix(n) } @_inlineable // FIXME(sil-serialize-all) public func prefix(_ maxLength: Int) -> SubSequence { @@ -108,10 +108,10 @@ extension _SequenceWrapper where SubSequence == Base.SubSequence { } @_inlineable // FIXME(sil-serialize-all) - public func drop( + public func removingPrefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { - return try _base.drop(while: predicate) + return try _base.removingPrefix(while: predicate) } @_inlineable // FIXME(sil-serialize-all) diff --git a/stdlib/public/core/Slice.swift.gyb b/stdlib/public/core/Slice.swift.gyb index 77bc621742497..d637a7344a75c 100644 --- a/stdlib/public/core/Slice.swift.gyb +++ b/stdlib/public/core/Slice.swift.gyb @@ -434,11 +434,11 @@ public struct ${Self} /// by using methods that return a subsequence. /// /// let singleDigits = 0...9 - /// let subSequence = singleDigits.dropFirst(5) + /// let subSequence = singleDigits.removingPrefix(5) /// print(Array(subSequence)) /// // Prints "[5, 6, 7, 8, 9]" /// - /// In this example, the expression `singleDigits.dropFirst(5))` is + /// In this example, the expression `singleDigits.removingPrefix(5))` is /// equivalent to calling this initializer with `singleDigits` and a /// range covering the last five items of `singleDigits.indices`. /// @@ -468,7 +468,7 @@ public struct ${Self} /// to `singleDigits`. /// /// let singleDigits = 0..<10 - /// let singleNonZeroDigits = singleDigits.dropFirst() + /// let singleNonZeroDigits = singleDigits.removingFirst() /// // singleNonZeroDigits is a RandomAccessSlice> /// /// print(singleNonZeroDigits.count) diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift index 733911277907b..fd899cd3938b7 100644 --- a/stdlib/public/core/String.swift +++ b/stdlib/public/core/String.swift @@ -436,7 +436,7 @@ extension String { /// that point: /// /// let name = "Marie Curie" -/// let firstSpace = name.index(of: " ") ?? name.endIndex +/// let firstSpace = name.firstIndex(of: " ") ?? name.endIndex /// let firstName = name[.. String.CharacterView in - /// if let i = chars.index(of: " ") { + /// if let i = chars.firstIndex(of: " ") { /// let result = chars[chars.index(after: i)...] /// chars.removeSubrange(i...) /// return result @@ -631,7 +631,7 @@ extension String.CharacterView : BidirectionalCollection { /// letter and then prints the character at the found index: /// /// let greeting = "Hello, friend!" - /// if let i = greeting.characters.index(where: { "A"..."Z" ~= $0 }) { + /// if let i = greeting.characters.firstIndex(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.characters[i])") /// } /// // Prints "First capital letter: H" @@ -764,7 +764,7 @@ extension String.CharacterView { /// not including, the first comma (`","`) in the string. /// /// let str = "All this happened, more or less." - /// let i = str.characters.index(of: ",")! + /// let i = str.characters.firstIndex(of: ",")! /// let substring = str.characters[str.characters.startIndex ..< i] /// print(String(substring)) /// // Prints "All this happened" diff --git a/stdlib/public/core/StringIndexConversions.swift b/stdlib/public/core/StringIndexConversions.swift index f828a358d1be4..cc22dd1501322 100644 --- a/stdlib/public/core/StringIndexConversions.swift +++ b/stdlib/public/core/StringIndexConversions.swift @@ -26,7 +26,7 @@ extension String.Index { /// print(cafe) /// // Prints "Cafรฉ" /// - /// let scalarsIndex = cafe.unicodeScalars.index(of: "e")! + /// let scalarsIndex = cafe.unicodeScalars.firstIndex(of: "e")! /// let stringIndex = String.Index(scalarsIndex, within: cafe)! /// /// print(cafe[...stringIndex]) @@ -68,7 +68,7 @@ extension String.Index { /// uses this method find the same position in the string's `utf8` view. /// /// let cafe = "Cafรฉ" - /// if let i = cafe.index(of: "รฉ") { + /// if let i = cafe.firstIndex(of: "รฉ") { /// let j = i.samePosition(in: cafe.utf8)! /// print(Array(cafe.utf8[j...])) /// } @@ -97,7 +97,7 @@ extension String.Index { /// uses this method find the same position in the string's `utf16` view. /// /// let cafe = "Cafรฉ" - /// if let i = cafe.index(of: "รฉ") { + /// if let i = cafe.firstIndex(of: "รฉ") { /// let j = i.samePosition(in: cafe.utf16)! /// print(cafe.utf16[j]) /// } diff --git a/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb b/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb index 5af0bcd3cb02e..21ee8dd2efceb 100644 --- a/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb +++ b/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb @@ -196,9 +196,9 @@ extension String : StringProtocol, RangeReplaceableCollection { /// For example, this code finds the first letter after the first space: /// /// let str = "Greetings, friend! How are you?" - /// let firstSpace = str.index(of: " ") ?? str.endIndex + /// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex /// let substr = str[firstSpace...] - /// if let nextCapital = substr.index(where: { $0 >= "A" && $0 <= "Z" }) { + /// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) { /// print("Capital after a space: \(str[nextCapital])") /// } /// // Prints "Capital after a space: H" @@ -350,7 +350,7 @@ extension String { /// removes the hyphen from the middle of a string. /// /// var nonempty = "non-empty" - /// if let i = nonempty.index(of: "-") { + /// if let i = nonempty.firstIndex(of: "-") { /// nonempty.remove(at: i) /// } /// print(nonempty) diff --git a/stdlib/public/core/StringUTF16.swift b/stdlib/public/core/StringUTF16.swift index d29056495c623..f4bcf1a897487 100644 --- a/stdlib/public/core/StringUTF16.swift +++ b/stdlib/public/core/StringUTF16.swift @@ -55,7 +55,7 @@ extension String { /// `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is ๐ŸŽ‰" - /// if let i = favemoji.utf16.index(where: { $0 >= 128 }) { + /// if let i = favemoji.utf16.firstIndex(where: { $0 >= 128 }) { /// let asciiPrefix = String(favemoji.utf16[..> 2 + 1 - nextBuffer.removeFirst(n8) + nextBuffer.removePrefix(n8) } if _fastPath(!nextBuffer.isEmpty) { @@ -398,7 +398,7 @@ extension String { /// another string's `utf8` view. /// /// let picnicGuest = "Deserving porcupine" - /// if let i = picnicGuest.utf8.index(of: 32) { + /// if let i = picnicGuest.utf8.firstIndex(of: 32) { /// let adjective = String(picnicGuest.utf8[..= 128 }) { + /// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) { /// let asciiPrefix = String(favemoji.unicodeScalars[.. String.Element? { guard !isEmpty else { return nil } let element = first! @@ -715,7 +715,7 @@ extension String { extension String.CharacterView { @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, obsoleted: 4, message: - "Please use 'first', 'dropFirst()', or 'Substring.CharacterView.popFirst()'.") + "Please use 'first', 'removingFirst()', or 'Substring.CharacterView.popFirst()'.") public mutating func popFirst() -> String.CharacterView.Element? { guard !isEmpty else { return nil } let element = first! @@ -727,7 +727,7 @@ extension String.CharacterView { extension String.UnicodeScalarView { @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, obsoleted: 4, message: - "Please use 'first', 'dropFirst()', or 'Substring.UnicodeScalarView.popFirst()'.") + "Please use 'first', 'removingFirst()', or 'Substring.UnicodeScalarView.popFirst()'.") public mutating func popFirst() -> String.UnicodeScalarView.Element? { guard !isEmpty else { return nil } let element = first! diff --git a/test/Constraints/generics.swift b/test/Constraints/generics.swift index fc46cf5d95d8d..598a1c5934857 100644 --- a/test/Constraints/generics.swift +++ b/test/Constraints/generics.swift @@ -499,8 +499,8 @@ extension Sequence { func rdar27700622(_ input: [E]) -> [E] { let pivot = input.first! - let lhs = input.dropFirst().filter { $0 <= pivot } - let rhs = input.dropFirst().filter { $0 > pivot } + let lhs = input.removingFirst().filter { $0 <= pivot } + let rhs = input.removingFirst().filter { $0 > pivot } return rdar27700622(lhs) + [pivot] + rdar27700622(rhs) // Ok } diff --git a/test/IDE/complete_from_stdlib.swift b/test/IDE/complete_from_stdlib.swift index eb3e0f5cffc70..a41be79948f98 100644 --- a/test/IDE/complete_from_stdlib.swift +++ b/test/IDE/complete_from_stdlib.swift @@ -135,8 +135,8 @@ func testArchetypeReplacement1(_ a: [FOO]) { // PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/CurrNominal: popLast()[#Equatable?#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceVar]/Super: isEmpty[#Bool#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceVar]/Super: first[#Equatable?#]{{; name=.+}} -// PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: dropFirst({#(n): Int#})[#ArraySlice#]{{; name=.+}} -// PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: dropLast({#(n): Int#})[#ArraySlice#]{{; name=.+}} +// PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: removingPrefix({#(n): Int#})[#ArraySlice#]{{; name=.+}} +// PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: removingSuffix({#(n): Int#})[#ArraySlice#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: prefix({#(maxLength): Int#})[#ArraySlice#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_5-DAG: Decl[InstanceMethod]/Super: suffix({#(maxLength): Int#})[#ArraySlice#]{{; name=.+}} @@ -149,14 +149,14 @@ func testArchetypeReplacement2(_ a: [BAR]) { // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/CurrNominal: append({#(newElement): Equatable#})[#Void#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/CurrNominal: insert({#(newElement): Equatable#}, {#at: Int#})[#Void#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/CurrNominal: popLast()[#Equatable?#]{{; name=.+}} -// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: dropFirst()[#ArraySlice#]{{; name=.+}} -// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: dropLast()[#ArraySlice#]{{; name=.+}} +// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: removingFirst()[#ArraySlice#]{{; name=.+}} +// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: removingLast()[#ArraySlice#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: enumerated()[#EnumeratedSequence<[Equatable]>#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: min({#by: (Equatable, Equatable) throws -> Bool##(Equatable, Equatable) throws -> Bool#})[' rethrows'][#Equatable?#]{{; name=.+}} // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: max({#by: (Equatable, Equatable) throws -> Bool##(Equatable, Equatable) throws -> Bool#})[' rethrows'][#Equatable?#]{{; name=.+}} // FIXME: The following should include 'partialResult' as local parameter name: "(nextPartialResult): (_ partialResult: Result, Equatable)" // PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: reduce({#(initialResult): Result#}, {#(nextPartialResult): (Result, Equatable) throws -> Result##(Result, Equatable) throws -> Result#})[' rethrows'][#Result#]{{; name=.+}} -// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: dropFirst({#(n): Int#})[#ArraySlice#]{{; name=.+}} +// PRIVATE_NOMINAL_MEMBERS_6-DAG: Decl[InstanceMethod]/Super: removingPrefix({#(n): Int#})[#ArraySlice#]{{; name=.+}} // FIXME: restore Decl[InstanceMethod]/Super: flatMap({#(transform): (Equatable) throws -> Sequence##(Equatable) throws -> Sequence#})[' rethrows'][#[IteratorProtocol.Element]#]{{; name=.+}} func testArchetypeReplacement3 (_ a : [Int]) { @@ -169,7 +169,7 @@ func testArchetypeReplacement3 (_ a : [Int]) { // PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceMethod]/CurrNominal: popLast()[#Int?#] // PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceVar]/Super: first[#Int?#] // PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceMethod]/Super: map({#(transform): (Int) throws -> T##(Int) throws -> T#})[' rethrows'][#[T]#] -// PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceMethod]/Super: dropLast({#(n): Int#})[#ArraySlice#] +// PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceMethod]/Super: removingSuffix({#(n): Int#})[#ArraySlice#] // PRIVATE_NOMINAL_MEMBERS_7-DAG: Decl[InstanceMethod]/Super: elementsEqual({#(other): Sequence#}, {#by: (Int, Int) throws -> Bool##(Int, Int) throws -> Bool#})[' rethrows'][#Bool#] @@ -222,7 +222,7 @@ func testArchetypeReplacement6() { struct Test1000 : Sequence { func #^RETURNS_ANY_SEQUENCE^# } -// RETURNS_ANY_SEQUENCE: Decl[InstanceMethod]/Super: dropFirst(_ n: Int) +// RETURNS_ANY_SEQUENCE: Decl[InstanceMethod]/Super: removingPrefix(_ n: Int) func testPostfixOperator1(_ x: Int) { x#^POSTFIX_INT_1^# diff --git a/test/IRGen/big_types_corner_cases.swift b/test/IRGen/big_types_corner_cases.swift index 148734486a6e8..3b68321728f05 100644 --- a/test/IRGen/big_types_corner_cases.swift +++ b/test/IRGen/big_types_corner_cases.swift @@ -192,7 +192,7 @@ public struct MUseStruct { // CHECK: ret void public func stringAndSubstring() -> (String, Substring) { let s = "Hello, World" - let a = Substring(s).dropFirst() + let a = Substring(s).removingFirst() return (s, a) } diff --git a/test/Interpreter/SDK/Foundation_test.swift b/test/Interpreter/SDK/Foundation_test.swift index 50dfc968b3f6e..a1ac601f8d128 100644 --- a/test/Interpreter/SDK/Foundation_test.swift +++ b/test/Interpreter/SDK/Foundation_test.swift @@ -163,8 +163,8 @@ FoundationTestSuite.test("RangeConversion") { expectEqual("{0, 5}", NSStringFromRange(nsrFromPartial)) let s = "Hello, ๐ŸŒŽ!" - let b = s.index(of: ",")! - let e = s.index(of: "!")! + let b = s.firstIndex(of: ",")! + let e = s.firstIndex(of: "!")! let nsr = NSRange(b..(_ x: E) {} func test_Equatable() { // CHECK-NEXT: Found 2.5 at index 1 let array: [NSNumber] = [1, 2.5, 3.14159] - if let index = array.index(of: 2.5) { + if let index = array.firstIndex(of: 2.5) { print("Found \(array[index]) at index \(index)") } else { print("Did not find 2.5?") diff --git a/test/Prototypes/BigInt.swift b/test/Prototypes/BigInt.swift index 56374da8992e1..1a9e0431d347c 100644 --- a/test/Prototypes/BigInt.swift +++ b/test/Prototypes/BigInt.swift @@ -712,7 +712,7 @@ public struct _BigInt : return 0 } - let i = _data.index(where: { $0 != 0 })! + let i = _data.firstIndex(where: { $0 != 0 })! _sanityCheck(_data[i] != 0) return i * Word.bitWidth + _data[i].trailingZeroBitCount } @@ -935,7 +935,7 @@ public struct _BigInt : // Check for a single prefixing hyphen let negative = source.hasPrefix("-") if negative { - source = String(source.characters.dropFirst()) + source = String(source.characters.removingFirst()) } // Loop through characters, multiplying diff --git a/test/Prototypes/CollectionTransformers.swift b/test/Prototypes/CollectionTransformers.swift index 1d2b0a11fce38..f272086ca7627 100644 --- a/test/Prototypes/CollectionTransformers.swift +++ b/test/Prototypes/CollectionTransformers.swift @@ -815,7 +815,7 @@ final public class ForkJoinPool { if ForkJoinPool._getCurrentThread() != nil { // Run the first task in this thread, fork the rest. let first = tasks.first - for t in tasks.dropFirst() { + for t in tasks.removingFirst() { // FIXME: optimize forking in bulk. t.fork() } diff --git a/test/Prototypes/PatternMatching.swift b/test/Prototypes/PatternMatching.swift index b34056b7e5374..7ec9bbed6f5a5 100644 --- a/test/Prototypes/PatternMatching.swift +++ b/test/Prototypes/PatternMatching.swift @@ -144,7 +144,7 @@ where M0.Element == M1.Element, M0.Index == M1.Index { return .notFound(resumeAt: nil) } // backtrack - src0 = src0.dropLast() + src0 = src0.removingLast() } case .notFound(let j): return .notFound(resumeAt: j) @@ -170,7 +170,7 @@ struct RepeatMatch : Pattern { , C.SubSequence : Collection { var lastEnd = c.startIndex - var rest = c.dropFirst(0) + var rest = c.removingPrefix(0) var data: MatchData = [] searchLoop: diff --git a/test/Prototypes/UnicodeDecoders.swift b/test/Prototypes/UnicodeDecoders.swift index ef9e6cba7a7ad..4fd5115b3b05d 100644 --- a/test/Prototypes/UnicodeDecoders.swift +++ b/test/Prototypes/UnicodeDecoders.swift @@ -280,7 +280,7 @@ func checkDecodeUTF( expectEqual(1, errorCount) let x = (expected + expectedRepairedTail).reversed() expectTrue( - x.starts(with: decoded), + x.hasPrefix(decoded), "reverse, repairing: false\n\t\(Array(x)) does not start with \(decoded)") decoded.removeAll(keepingCapacity: true) } @@ -321,10 +321,10 @@ func checkDecodeUTF( do { let s0 = "\n" + String(decoding: utfStr, as: Codec.self) + "\n" - let s = s0.dropFirst().dropLast() + let s = s0.removingFirst().removingLast() expectEqualSequence(expected, utf32(s), "Sliced Substring") checkStringProtocol( - s0.dropFirst().dropLast(), + s0.removingFirst().removingLast(), utfStr, encodedAs: Codec.self, expectingUTF32: expected) } diff --git a/test/stdlib/ArrayDiagnostics.swift b/test/stdlib/ArrayDiagnostics.swift index d1f6f6b3d6074..1a656c2eedc6f 100644 --- a/test/stdlib/ArrayDiagnostics.swift +++ b/test/stdlib/ArrayDiagnostics.swift @@ -1,4 +1,4 @@ -// RUN: %target-typecheck-verify-swift +// RUN: %target-typecheck-verify-swift -swift-version 4.1 class NotEquatable {} @@ -9,3 +9,45 @@ func test_ArrayOfNotEquatableIsNotEquatable() { // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } +func test_SE0132Deprecations() { + var a = [1, 2, 3] + + _ = a.index(of: 2) // expected-warning {{'index(of:)' is deprecated: renamed to 'firstIndex(of:)'}} + // expected-note @-1 {{use 'firstIndex(of:)' instead}} {{9-14=firstIndex}} + + _ = a.index(where: { $0 == 2}) // expected-warning {{'index(where:)' is deprecated: renamed to 'firstIndex(where:)'}} + // expected-note @-1 {{use 'firstIndex(where:)' instead}} {{9-14=firstIndex}} + + _ = a.index { $0 == 2 } // expected-warning {{'index(where:)' is deprecated: renamed to 'firstIndex(where:)'}} + // expected-note @-1 {{use 'firstIndex(where:)' instead}} {{9-14=firstIndex}} + + _ = a.starts(with: [1, 2]) // expected-warning {{'starts(with:)' is deprecated: renamed to 'hasPrefix(_:)'}} + // expected-note @-1 {{use 'hasPrefix(_:)' instead}} {{9-15=hasPrefix}} {{16-22=}} + + _ = a.starts(with: [1, 2], by: ==) // expected-warning {{'starts(with:by:)' is deprecated: renamed to 'hasPrefix(_:by:)'}} + // expected-note @-1 {{use 'hasPrefix(_:by:)' instead}} {{9-15=hasPrefix}} {{16-22=}} + + _ = a.removeFirst(1) // expected-warning {{'removeFirst' is deprecated: renamed to 'removePrefix(_:)'}} + // expected-note @-1 {{use 'removePrefix(_:)' instead}} {{9-20=removePrefix}} + + _ = a.removeLast(1) // expected-warning {{'removeLast' is deprecated: renamed to 'removeSuffix(_:)'}} + // expected-note @-1 {{use 'removeSuffix(_:)' instead}} {{9-19=removeSuffix}} + + _ = a.dropFirst(1) // expected-warning {{'dropFirst' is deprecated: renamed to 'removingPrefix(_:)'}} + // expected-note @-1 {{use 'removingPrefix(_:)' instead}} {{9-18=removingPrefix}} + + _ = a.dropLast(1) // expected-warning {{'dropLast' is deprecated: renamed to 'removingSuffix(_:)'}} + // expected-note @-1 {{use 'removingSuffix(_:)' instead}} {{9-17=removingSuffix}} + + _ = a.dropFirst() // expected-warning {{'dropFirst()' is deprecated: renamed to 'removingFirst()'}} + // expected-note @-1 {{use 'removingFirst()' instead}} {{9-18=removingFirst}} + + _ = a.dropLast() // expected-warning {{'dropLast()' is deprecated: renamed to 'removingLast()'}} + // expected-note @-1 {{use 'removingLast()' instead}} {{9-17=removingLast}} + + _ = a.drop(while: { $0 == 2 }) // expected-warning {{'drop(while:)' is deprecated: renamed to 'removingPrefix(while:)'}} + // expected-note @-1 {{use 'removingPrefix(while:)' instead}} {{9-13=removingPrefix}} + + _ = a.drop { $0 == 2 } // expected-warning {{'drop(while:)' is deprecated: renamed to 'removingPrefix(while:)'}} + // expected-note @-1 {{use 'removingPrefix(while:)' instead}} {{9-13=removingPrefix}} +} diff --git a/test/stdlib/ErrorHandling.swift b/test/stdlib/ErrorHandling.swift index ec974f72f890d..4db07f3aff53e 100644 --- a/test/stdlib/ErrorHandling.swift +++ b/test/stdlib/ErrorHandling.swift @@ -95,9 +95,9 @@ ErrorHandlingTests.test("ErrorHandling/withCString extends lifetime") { // TODO: Some way to check string was deallocated? } -ErrorHandlingTests.test("ErrorHandling/index(where:)") { +ErrorHandlingTests.test("ErrorHandling/firstIndex(where:)") { do { - let _: Int? = try [1, 2, 3].index { + let _: Int? = try [1, 2, 3].firstIndex { throw SillyError.JazzHands return $0 == $0 } @@ -190,9 +190,9 @@ ErrorHandlingTests.test("ErrorHandling/min") { } catch {} } -ErrorHandlingTests.test("ErrorHandling/starts(with:)") { +ErrorHandlingTests.test("ErrorHandling/hasPrefix(_:)") { do { - let x: Bool = try [1, 2, 3].starts(with: [1, 2]) { _, _ in + let x: Bool = try [1, 2, 3].hasPrefix([1, 2]) { _, _ in throw SillyError.JazzHands return false } diff --git a/test/stdlib/Mirror.swift b/test/stdlib/Mirror.swift index 03fd4a90b6d3a..595d2a737bfd7 100644 --- a/test/stdlib/Mirror.swift +++ b/test/stdlib/Mirror.swift @@ -111,7 +111,7 @@ mirrors.test("BidirectionalStructure") { let description = y.testDescription expectEqual( "[nil: \"a\", nil: \"b\", nil: \"c\", nil: \"", - description[description.startIndex.. = [ 10 ] - let index = s.index(of: 10)! + let index = s.firstIndex(of: 10)! s.remove(at: index) expectFalse(s.contains(10)) expectCrashLater() diff --git a/test/stdlib/StringAPI.swift b/test/stdlib/StringAPI.swift index 99c629e66ed58..93a3d1f04a814 100644 --- a/test/stdlib/StringAPI.swift +++ b/test/stdlib/StringAPI.swift @@ -269,11 +269,11 @@ func checkHasPrefixHasSuffix( rhs.decomposedStringWithCanonicalMapping.characters.map { Array(String($0).unicodeScalars) } - let expectHasPrefix = lhsNFDGraphemeClusters.starts( - with: rhsNFDGraphemeClusters, by: (==)) + let expectHasPrefix = lhsNFDGraphemeClusters.hasPrefix( + rhsNFDGraphemeClusters, by: (==)) let expectHasSuffix = lhsNFDGraphemeClusters.lazy.reversed() - .starts(with: rhsNFDGraphemeClusters.lazy.reversed(), by: (==)) + .hasPrefix(rhsNFDGraphemeClusters.lazy.reversed(), by: (==)) expectEqual(expectHasPrefix, lhs.hasPrefix(rhs), stackTrace: stackTrace) expectEqual(expectHasSuffix, lhs.hasSuffix(rhs), stackTrace: stackTrace) @@ -377,7 +377,7 @@ StringTests.test("UnicodeScalarView.Iterator.Lifetime") { for s in sources { // Append something to s so that it creates a dynamically-allocated buffer. let i = (s + "X").unicodeScalars.makeIterator() - expectEqualSequence(s.unicodeScalars, IteratorSequence(i).dropLast(), + expectEqualSequence(s.unicodeScalars, IteratorSequence(i).removingLast(), "Actual Contents: \(Array(IteratorSequence(i)))") } } diff --git a/test/stdlib/StringCompatibilityDiagnostics.swift b/test/stdlib/StringCompatibilityDiagnostics.swift index 352c6f114fb2c..a6ffe1bfa4e8d 100644 --- a/test/stdlib/StringCompatibilityDiagnostics.swift +++ b/test/stdlib/StringCompatibilityDiagnostics.swift @@ -2,9 +2,9 @@ func testPopFirst() { var str = "abc" - _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}} + _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'removingFirst()', or 'Substring.popFirst()'}} _ = str.characters.popFirst() // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} - _ = str.unicodeScalars.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} + _ = str.unicodeScalars.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'removingFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} var charView: String.CharacterView // expected-warning{{'CharacterView' is deprecated: Please use String or Substring directly}} charView = str.characters // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} diff --git a/test/stdlib/StringCompatibilityDiagnostics3.swift b/test/stdlib/StringCompatibilityDiagnostics3.swift index c9358ac1cbdd6..dc2d14833218d 100644 --- a/test/stdlib/StringCompatibilityDiagnostics3.swift +++ b/test/stdlib/StringCompatibilityDiagnostics3.swift @@ -2,10 +2,10 @@ func testPopFirst() { var str = "abc" - _ = str.popFirst() // expected-warning{{'popFirst()' is deprecated: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}} + _ = str.popFirst() // expected-warning{{'popFirst()' is deprecated: Please use 'first', 'removingFirst()', or 'Substring.popFirst()'}} _ = str.characters.popFirst() // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} - // expected-warning@-1{{'popFirst()' is deprecated: Please use 'first', 'dropFirst()', or 'Substring.CharacterView.popFirst()'}} - _ = str.unicodeScalars.popFirst() // expected-warning{{'popFirst()' is deprecated: Please use 'first', 'dropFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} + // expected-warning@-1{{'popFirst()' is deprecated: Please use 'first', 'removingFirst()', or 'Substring.CharacterView.popFirst()'}} + _ = str.unicodeScalars.popFirst() // expected-warning{{'popFirst()' is deprecated: Please use 'first', 'removingFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} var charView: String.CharacterView // expected-warning{{'CharacterView' is deprecated: Please use String or Substring directly}} charView = str.characters // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} diff --git a/test/stdlib/StringCompatibilityDiagnostics4.swift b/test/stdlib/StringCompatibilityDiagnostics4.swift index b5fb753d2c678..384f9030ad27c 100644 --- a/test/stdlib/StringCompatibilityDiagnostics4.swift +++ b/test/stdlib/StringCompatibilityDiagnostics4.swift @@ -2,10 +2,10 @@ func testPopFirst() { var str = "abc" - _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}} + _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'removingFirst()', or 'Substring.popFirst()'}} _ = str.characters.popFirst() // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} - _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}} - _ = str.unicodeScalars.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} + _ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'removingFirst()', or 'Substring.popFirst()'}} + _ = str.unicodeScalars.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'removingFirst()', or 'Substring.UnicodeScalarView.popFirst()'}} var charView: String.CharacterView // expected-warning{{'CharacterView' is deprecated: Please use String or Substring directly}} charView = str.characters // expected-warning{{'characters' is deprecated: Please use String or Substring directly}} diff --git a/test/stdlib/TestData.swift b/test/stdlib/TestData.swift index 70792c1917471..b8053ee2b6247 100644 --- a/test/stdlib/TestData.swift +++ b/test/stdlib/TestData.swift @@ -1152,9 +1152,9 @@ class TestData : TestDataSuper { expectEqual(expected, actual) } - func test_dropFirst() { + func test_removingFirst() { var data = Data([0, 1, 2, 3, 4, 5]) - let sliced = data.dropFirst() + let sliced = data.removingFirst() expectEqual(data.count - 1, sliced.count) expectEqual(UInt8(1), sliced[1]) expectEqual(UInt8(2), sliced[2]) @@ -1163,9 +1163,9 @@ class TestData : TestDataSuper { expectEqual(UInt8(5), sliced[5]) } - func test_dropFirst2() { + func test_removingPrefix2() { var data = Data([0, 1, 2, 3, 4, 5]) - let sliced = data.dropFirst(2) + let sliced = data.removingPrefix(2) expectEqual(data.count - 2, sliced.count) expectEqual(UInt8(2), sliced[2]) expectEqual(UInt8(3), sliced[3]) @@ -3733,8 +3733,8 @@ DataTests.test("test_sliceEquality") { TestData().test_sliceEquality() } DataTests.test("test_sliceEquality2") { TestData().test_sliceEquality2() } DataTests.test("test_splittingHttp") { TestData().test_splittingHttp() } DataTests.test("test_map") { TestData().test_map() } -DataTests.test("test_dropFirst") { TestData().test_dropFirst() } -DataTests.test("test_dropFirst2") { TestData().test_dropFirst2() } +DataTests.test("test_removingPrefix") { TestData().test_removingFirst() } +DataTests.test("test_removingPrefix2") { TestData().test_removingPrefix2() } DataTests.test("test_copyBytes1") { TestData().test_copyBytes1() } DataTests.test("test_copyBytes2") { TestData().test_copyBytes2() } DataTests.test("test_sliceOfSliceViaRangeExpression") { TestData().test_sliceOfSliceViaRangeExpression() } diff --git a/test/stdlib/TestIndexPath.swift b/test/stdlib/TestIndexPath.swift index 79112b9ac9c8f..5f65505c70cbd 100644 --- a/test/stdlib/TestIndexPath.swift +++ b/test/stdlib/TestIndexPath.swift @@ -77,7 +77,7 @@ class TestIndexPath: TestIndexPathSuper { func testDropLast() { let ip: IndexPath = [1, 2, 3, 4] - let ip2 = ip.dropLast() + let ip2 = ip.removingLast() expectEqual(ip2.count, 3) expectEqual(ip2[0], 1) expectEqual(ip2[1], 2) @@ -86,26 +86,26 @@ class TestIndexPath: TestIndexPathSuper { func testDropLastFromEmpty() { let ip: IndexPath = [] - let ip2 = ip.dropLast() + let ip2 = ip.removingLast() expectEqual(ip2.count, 0) } func testDropLastFromSingle() { let ip: IndexPath = [1] - let ip2 = ip.dropLast() + let ip2 = ip.removingLast() expectEqual(ip2.count, 0) } func testDropLastFromPair() { let ip: IndexPath = [1, 2] - let ip2 = ip.dropLast() + let ip2 = ip.removingLast() expectEqual(ip2.count, 1) expectEqual(ip2[0], 1) } func testDropLastFromTriple() { let ip: IndexPath = [1, 2, 3] - let ip2 = ip.dropLast() + let ip2 = ip.removingLast() expectEqual(ip2.count, 2) expectEqual(ip2[0], 1) expectEqual(ip2[1], 2) @@ -714,18 +714,18 @@ class TestIndexPath: TestIndexPathSuper { func test_slice_1ary() { let indexPath: IndexPath = [0] - let res = indexPath.dropFirst() + let res = indexPath.removingFirst() expectEqual(0, res.count) let slice = indexPath[1..<1] expectEqual(0, slice.count) } - func test_dropFirst() { + func test_removingFirst() { var pth = IndexPath(indexes:[1,2,3,4]) while !pth.isEmpty { // this should not crash - pth = pth.dropFirst() + pth = pth.removingFirst() } } } @@ -780,6 +780,6 @@ IndexPathTests.test("test_AnyHashableContainingIndexPath") { TestIndexPath().tes IndexPathTests.test("test_AnyHashableCreatedFromNSIndexPath") { TestIndexPath().test_AnyHashableCreatedFromNSIndexPath() } IndexPathTests.test("test_unconditionallyBridgeFromObjectiveC") { TestIndexPath().test_unconditionallyBridgeFromObjectiveC() } IndexPathTests.test("test_slice_1ary") { TestIndexPath().test_slice_1ary() } -IndexPathTests.test("test_dropFirst") { TestIndexPath().test_dropFirst() } +IndexPathTests.test("test_removingPrefix") { TestIndexPath().test_removingFirst() } runAllTests() #endif diff --git a/test/stdlib/subString.swift b/test/stdlib/subString.swift index 3ed4d7cba2c70..197acbbe8c141 100644 --- a/test/stdlib/subString.swift +++ b/test/stdlib/subString.swift @@ -22,8 +22,8 @@ SubstringTests.test("Equality") { expectEqual(s1, "cd") expectEqual(s2, "cd") expectEqual(s3, "cd") - expectTrue("" == s.dropFirst(s.count)) - expectTrue(s.dropFirst().dropFirst(s.count) == s.dropFirst(s.count)) + expectTrue("" == s.removingPrefix(s.count)) + expectTrue(s.removingFirst().removingPrefix(s.count) == s.removingPrefix(s.count)) expectEqual("ab" as String, s.prefix(2)) expectEqual("fg" as String, s.suffix(2)) @@ -32,24 +32,24 @@ SubstringTests.test("Equality") { let emoji: String = s + "๐Ÿ˜„๐Ÿ‘๐Ÿฝ๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ" + "๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช๐Ÿ‡จ๐Ÿ‡ฆ๐Ÿ‡ฎ๐Ÿ‡ณ" expectTrue(s == s[...]) expectTrue(s[...] == s) - expectTrue(s.dropFirst(2) != s) - expectTrue(s == s.dropFirst(0)) - expectTrue(s != s.dropFirst(1)) - expectTrue(s != s.dropLast(1)) + expectTrue(s.removingPrefix(2) != s) + expectTrue(s == s.removingPrefix(0)) + expectTrue(s != s.removingPrefix(1)) + expectTrue(s != s.removingSuffix(1)) expectEqual(s[...], s[...]) - expectEqual(s.dropFirst(0), s.dropFirst(0)) - expectTrue(s == s.dropFirst(0)) - expectTrue(s.dropFirst(2) != s.dropFirst(1)) - expectNotEqual(s.dropLast(2), s.dropLast(1)) - expectEqual(s.dropFirst(1), s.dropFirst(1)) - expectTrue(s != s[...].dropFirst(1)) - let i = emoji.index(of: "๐Ÿ˜„")! + expectEqual(s.removingPrefix(0), s.removingPrefix(0)) + expectTrue(s == s.removingPrefix(0)) + expectTrue(s.removingPrefix(2) != s.removingPrefix(1)) + expectNotEqual(s.removingSuffix(2), s.removingSuffix(1)) + expectEqual(s.removingPrefix(1), s.removingPrefix(1)) + expectTrue(s != s[...].removingPrefix(1)) + let i = emoji.firstIndex(of: "๐Ÿ˜„")! expectEqual("๐Ÿ˜„๐Ÿ‘๐Ÿฝ" as String, emoji[i...].prefix(2)) - expectTrue("๐Ÿ˜„๐Ÿ‘๐Ÿฝ๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String == emoji[i...].dropLast(2)) - expectTrue("๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String == emoji[i...].dropLast(2).dropFirst(2)) - expectTrue(s as String != emoji[i...].dropLast(2).dropFirst(2)) - expectEqualSequence("๐Ÿ˜„๐Ÿ‘๐Ÿฝ๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String, emoji[i...].dropLast(2)) - expectEqualSequence("๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String, emoji[i...].dropLast(2).dropFirst(2)) + expectTrue("๐Ÿ˜„๐Ÿ‘๐Ÿฝ๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String == emoji[i...].removingSuffix(2)) + expectTrue("๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String == emoji[i...].removingSuffix(2).removingPrefix(2)) + expectTrue(s as String != emoji[i...].removingSuffix(2).removingPrefix(2)) + expectEqualSequence("๐Ÿ˜„๐Ÿ‘๐Ÿฝ๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String, emoji[i...].removingSuffix(2)) + expectEqualSequence("๐Ÿ‡ซ๐Ÿ‡ท๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ™ˆ๐Ÿ˜ก๐Ÿ‡ง๐Ÿ‡ช" as String, emoji[i...].removingSuffix(2).removingPrefix(2)) #endif // equatable conformance expectTrue("one,two,three".split(separator: ",").contains("two")) @@ -72,20 +72,20 @@ SubstringTests.test("Comparison") { expectTrue(s[...] >= s[...]) expectFalse(s[...] > s[...]) - expectTrue(s < s.dropFirst()) - expectFalse(s > s.dropFirst()) - expectFalse(s < s.dropLast()) - expectTrue(s > s.dropLast()) - expectTrue(s.dropFirst() < s.dropFirst(2)) - expectFalse(s.dropFirst() > s.dropFirst(2)) - expectFalse(s.dropLast() < s.dropLast(2)) - expectTrue(s.dropLast() > s.dropLast(2)) - expectFalse(s.dropFirst() < s.dropFirst().dropLast()) - expectTrue(s.dropFirst() > s.dropFirst().dropLast()) - expectTrue(s.dropFirst() > s) - expectTrue(s.dropFirst() > s[...]) + expectTrue(s < s.removingFirst()) + expectFalse(s > s.removingFirst()) + expectFalse(s < s.removingLast()) + expectTrue(s > s.removingLast()) + expectTrue(s.removingFirst() < s.removingPrefix(2)) + expectFalse(s.removingFirst() > s.removingPrefix(2)) + expectFalse(s.removingLast() < s.removingSuffix(2)) + expectTrue(s.removingLast() > s.removingSuffix(2)) + expectFalse(s.removingFirst() < s.removingFirst().removingLast()) + expectTrue(s.removingFirst() > s.removingFirst().removingLast()) + expectTrue(s.removingFirst() > s) + expectTrue(s.removingFirst() > s[...]) expectTrue(s >= s[...]) - expectTrue(s.dropFirst() >= s.dropFirst()) + expectTrue(s.removingFirst() >= s.removingFirst()) // comparable conformance expectEqualSequence("pen,pineapple,apple,pen".split(separator: ",").sorted(), @@ -93,7 +93,7 @@ SubstringTests.test("Comparison") { } SubstringTests.test("Filter") { - var name = "๐Ÿ˜‚Edward Woodward".dropFirst() + var name = "๐Ÿ˜‚Edward Woodward".removingFirst() var filtered = name.filter { $0 != "d" } expectType(Substring.self, &name) expectType(String.self, &filtered) @@ -102,8 +102,8 @@ SubstringTests.test("Filter") { SubstringTests.test("CharacterView") { let s = "abcdefg" - var t = s.characters.dropFirst(2) - var u = t.dropFirst(2) + var t = s.characters.removingPrefix(2) + var u = t.removingPrefix(2) checkMatch(s.characters, t, t.startIndex) checkMatch(s.characters, t, t.index(after: t.startIndex)) @@ -114,10 +114,10 @@ SubstringTests.test("CharacterView") { checkMatch(t, u, u.index(after: u.startIndex)) checkMatch(t, u, u.index(before: u.endIndex)) - expectEqual("", String(t.dropFirst(10))) - expectEqual("", String(t.dropLast(10))) - expectEqual("", String(u.dropFirst(10))) - expectEqual("", String(u.dropLast(10))) + expectEqual("", String(t.removingPrefix(10))) + expectEqual("", String(t.removingSuffix(10))) + expectEqual("", String(u.removingPrefix(10))) + expectEqual("", String(u.removingSuffix(10))) t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"]) u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"]) @@ -128,8 +128,8 @@ SubstringTests.test("CharacterView") { SubstringTests.test("UnicodeScalars") { let s = "abcdefg" - var t = s.unicodeScalars.dropFirst(2) - var u = t.dropFirst(2) + var t = s.unicodeScalars.removingPrefix(2) + var u = t.removingPrefix(2) checkMatch(s.unicodeScalars, t, t.startIndex) checkMatch(s.unicodeScalars, t, t.index(after: t.startIndex)) @@ -140,10 +140,10 @@ SubstringTests.test("UnicodeScalars") { checkMatch(t, u, u.index(after: u.startIndex)) checkMatch(t, u, u.index(before: u.endIndex)) - expectEqual("", String(t.dropFirst(10))) - expectEqual("", String(t.dropLast(10))) - expectEqual("", String(u.dropFirst(10))) - expectEqual("", String(u.dropLast(10))) + expectEqual("", String(t.removingPrefix(10))) + expectEqual("", String(t.removingSuffix(10))) + expectEqual("", String(u.removingPrefix(10))) + expectEqual("", String(u.removingSuffix(10))) t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"]) u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"]) @@ -154,8 +154,8 @@ SubstringTests.test("UnicodeScalars") { SubstringTests.test("UTF16View") { let s = "abcdefg" - let t = s.utf16.dropFirst(2) - let u = t.dropFirst(2) + let t = s.utf16.removingPrefix(2) + let u = t.removingPrefix(2) checkMatch(s.utf16, t, t.startIndex) checkMatch(s.utf16, t, t.index(after: t.startIndex)) @@ -166,16 +166,16 @@ SubstringTests.test("UTF16View") { checkMatch(t, u, u.index(after: u.startIndex)) checkMatch(t, u, u.index(before: u.endIndex)) - expectEqual("", String(t.dropFirst(10))!) - expectEqual("", String(t.dropLast(10))!) - expectEqual("", String(u.dropFirst(10))!) - expectEqual("", String(u.dropLast(10))!) + expectEqual("", String(t.removingPrefix(10))!) + expectEqual("", String(t.removingSuffix(10))!) + expectEqual("", String(u.removingPrefix(10))!) + expectEqual("", String(u.removingSuffix(10))!) } SubstringTests.test("UTF8View") { let s = "abcdefg" - let t = s.utf8.dropFirst(2) - let u = t.dropFirst(2) + let t = s.utf8.removingPrefix(2) + let u = t.removingPrefix(2) checkMatch(s.utf8, t, t.startIndex) checkMatch(s.utf8, t, t.index(after: t.startIndex)) @@ -184,17 +184,17 @@ SubstringTests.test("UTF8View") { checkMatch(t, u, u.startIndex) checkMatch(t, u, u.index(after: u.startIndex)) - expectEqual("", String(t.dropFirst(10))!) - expectEqual("", String(t.dropLast(10))!) - expectEqual("", String(u.dropFirst(10))!) - expectEqual("", String(u.dropLast(10))!) + expectEqual("", String(t.removingPrefix(10))!) + expectEqual("", String(t.removingSuffix(10))!) + expectEqual("", String(u.removingPrefix(10))!) + expectEqual("", String(u.removingSuffix(10))!) } SubstringTests.test("Persistent Content") { var str = "abc" str += "def" - expectEqual("bcdefg", str.dropFirst(1) + "g") - expectEqual("bcdefg", (str.dropFirst(1) + "g") as String) + expectEqual("bcdefg", str.removingPrefix(1) + "g") + expectEqual("bcdefg", (str.removingPrefix(1) + "g") as String) } runAllTests() diff --git a/validation-test/Sema/type_checker_crashers_fixed/rdar28145033.swift b/validation-test/Sema/type_checker_crashers_fixed/rdar28145033.swift index 826f2249f9cf7..bcb2c653a2498 100644 --- a/validation-test/Sema/type_checker_crashers_fixed/rdar28145033.swift +++ b/validation-test/Sema/type_checker_crashers_fixed/rdar28145033.swift @@ -1,4 +1,4 @@ // RUN: not %target-swift-frontend %s -typecheck let a = [1] -_ = a.index(of: a.min()) // a.min() returns an optional +_ = a.firstIndex(of: a.min()) // a.min() returns an optional diff --git a/validation-test/compiler_crashers_2_fixed/0109-sr4737.swift b/validation-test/compiler_crashers_2_fixed/0109-sr4737.swift index 29643d57d4c27..00a552a6022f1 100644 --- a/validation-test/compiler_crashers_2_fixed/0109-sr4737.swift +++ b/validation-test/compiler_crashers_2_fixed/0109-sr4737.swift @@ -933,7 +933,7 @@ func checkDecodeUTF( expectEqual(1, errorCount) let x = (expected + expectedRepairedTail).reversed() expectTrue( - x.starts(with: decoded), + x.hasPrefix(decoded), "reverse, repairing: false\n\t\(Array(x)) does not start with \(decoded)") decoded.removeAll(keepingCapacity: true) } diff --git a/validation-test/stdlib/Algorithm.swift b/validation-test/stdlib/Algorithm.swift index 90076bd5e5d0c..829d88f4a0423 100644 --- a/validation-test/stdlib/Algorithm.swift +++ b/validation-test/stdlib/Algorithm.swift @@ -234,7 +234,7 @@ Algorithm.test("sort3/simple") } func isSorted(_ a: [T], by areInIncreasingOrder: (T, T) -> Bool) -> Bool { - return !a.dropFirst().enumerated().contains(where: { (offset, element) in + return !a.removingFirst().enumerated().contains(where: { (offset, element) in areInIncreasingOrder(element, a[offset]) }) } diff --git a/validation-test/stdlib/CollectionType.swift.gyb b/validation-test/stdlib/CollectionType.swift.gyb index 652274227329c..33cbc00747a1b 100644 --- a/validation-test/stdlib/CollectionType.swift.gyb +++ b/validation-test/stdlib/CollectionType.swift.gyb @@ -628,12 +628,12 @@ CollectionTypeTests.test("count/dispatch") { } //===----------------------------------------------------------------------===// -// index(of:) +// firstIndex(of:) //===----------------------------------------------------------------------===// -CollectionTypeTests.test("index(of:)/WhereElementIsEquatable/dispatch") { +CollectionTypeTests.test("firstIndex(of:)/WhereElementIsEquatable/dispatch") { let tester = CollectionLog.dispatchTester([MinimalEquatableValue(1)]) - _ = tester.index(of: MinimalEquatableValue(1)) + _ = tester.firstIndex(of: MinimalEquatableValue(1)) expectCustomizable(tester, tester.log._customIndexOfEquatableElement) } @@ -644,14 +644,14 @@ func callGenericFind_< C : Collection >(_ collection: C, _ element: C.Iterator.Element) -> C.Index? where C.Iterator.Element : Equatable { - return collection.index(of: element) + return collection.firstIndex(of: element) } func callStaticFind_( _ set: Set, _ element: MinimalHashableValue ) -> Set.Index? { - return set.index(of: element) + return set.firstIndex(of: element) } % for dispatch in [ 'Static', 'Generic' ]: @@ -706,7 +706,7 @@ extension Collection where func _test_indicesOf(_ element: Iterator.Element) -> [Index] { var result: [Index] = [] var tail = self[startIndex..=4.0) expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) #endif @@ -4397,11 +4397,11 @@ DictionaryTestSuite.test("misc") { expectOptionalEqual(4, d3["four"]) expectOptionalEqual(5, d3["five"]) - expectEqual(3, d.values[d.keys.index(of: "three")!]) - expectEqual(4, d.values[d.keys.index(of: "four")!]) + expectEqual(3, d.values[d.keys.firstIndex(of: "three")!]) + expectEqual(4, d.values[d.keys.firstIndex(of: "four")!]) - expectEqual(3, d3.values[d3.keys.index(of: "three")!]) - expectEqual(4, d3.values[d3.keys.index(of: "four")!]) + expectEqual(3, d3.values[d3.keys.firstIndex(of: "three")!]) + expectEqual(4, d3.values[d3.keys.firstIndex(of: "four")!]) } } diff --git a/validation-test/stdlib/ExistentialCollection.swift.gyb b/validation-test/stdlib/ExistentialCollection.swift.gyb index 2a65c853f202f..c8579e12aeb1e 100644 --- a/validation-test/stdlib/ExistentialCollection.swift.gyb +++ b/validation-test/stdlib/ExistentialCollection.swift.gyb @@ -163,16 +163,16 @@ tests.test("${TestedType}: dispatch to wrapped, SequenceLog") { _ = s.forEach { (_) in } } - Log.dropFirst.expectIncrement(Base.self) { - _ = s.dropFirst(0) + Log.removingPrefix.expectIncrement(Base.self) { + _ = s.removingPrefix(0) } - Log.dropLast.expectIncrement(Base.self) { - _ = s.dropLast(0) + Log.removingSuffix.expectIncrement(Base.self) { + _ = s.removingSuffix(0) } - Log.dropWhile.expectIncrement(Base.self) { - _ = s.drop { (_) in true } + Log.removingPrefixWhile.expectIncrement(Base.self) { + _ = s.removingPrefix { (_) in true } } Log.prefixWhile.expectIncrement(Base.self) { @@ -358,7 +358,7 @@ tests.test("ForwardCollection") { let a1 = ContiguousArray(fc0) expectEqual(a0, a1) for e in a0 { - let i = fc0.index(of: e) + let i = fc0.firstIndex(of: e) expectNotNil(i) expectEqual(e, fc0[i!]) } @@ -386,7 +386,7 @@ tests.test("BidirectionalCollection") { let a1 = ContiguousArray(bc0.lazy.reversed()) expectEqual(a0, a1) for e in a0 { - let i = bc0.index(of: e) + let i = bc0.firstIndex(of: e) expectNotNil(i) expectEqual(e, bc0[i!]) } @@ -421,7 +421,7 @@ tests.test("RandomAccessCollection") { let a1 = ContiguousArray(rc0.lazy.reversed()) expectEqual(a0, a1) for e in a0 { - let i = rc0.index(of: e) + let i = rc0.firstIndex(of: e) expectNotNil(i) expectEqual(e, rc0[i!]) } diff --git a/validation-test/stdlib/Lazy.swift.gyb b/validation-test/stdlib/Lazy.swift.gyb index 56c716bd776ec..670c7069ffa61 100644 --- a/validation-test/stdlib/Lazy.swift.gyb +++ b/validation-test/stdlib/Lazy.swift.gyb @@ -1389,7 +1389,7 @@ tests.test("LazyDropWhile${Self}").forEach(in: prefixDropWhileTests) { let base = Minimal${Self}(elements: data) var calls1 = 0 - let dropped = base.lazy.drop(while: { calls1 += 1; return $0 != value }) + let dropped = base.lazy.removingPrefix(while: { calls1 += 1; return $0 != value }) let expected = data.suffix(from: pivot) expectEqual(0, calls1) check${checkKind}(expected, dropped) diff --git a/validation-test/stdlib/SequenceType.swift.gyb b/validation-test/stdlib/SequenceType.swift.gyb index ae91910948eb7..841e920784e69 100644 --- a/validation-test/stdlib/SequenceType.swift.gyb +++ b/validation-test/stdlib/SequenceType.swift.gyb @@ -49,7 +49,7 @@ var SequenceTypeTests = TestSuite("Sequence") // // - NaN behavior of floating point types, combined with these generic // algorithms, should make sense if possible. For example, -// [1.0, Double.nan].starts(with: [1.0, 2.0]) should be false. +// [1.0, Double.nan].hasPrefix([1.0, 2.0]) should be false. //===----------------------------------------------------------------------===// // min(), max() @@ -274,11 +274,11 @@ SequenceTypeTests.test("enumerated()") { } //===----------------------------------------------------------------------===// -// starts(with:) +// hasPrefix(_:) //===----------------------------------------------------------------------===// -SequenceTypeTests.test("starts(with:)/WhereElementIsEquatable") { - for test in startsWithTests { +SequenceTypeTests.test("hasPrefix(_:)/WhereElementIsEquatable") { + for test in hasPrefixTests { do { let s = MinimalSequence( elements: test.sequence.map(MinimalEquatableValue.init)) @@ -286,7 +286,7 @@ SequenceTypeTests.test("starts(with:)/WhereElementIsEquatable") { elements: test.prefix.map(MinimalEquatableValue.init)) expectEqual( test.expected, - s.starts(with: prefix), + s.hasPrefix(prefix), stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.expectedLeftoverSequence, s.map { $0.value }, @@ -304,7 +304,7 @@ SequenceTypeTests.test("starts(with:)/WhereElementIsEquatable") { elements: test.prefix.map(MinimalEquatableValue.init)) expectEqual( test.expected, - s.starts(with: prefix), + s.hasPrefix(prefix), stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.sequence, s.map { $0.value }, @@ -316,8 +316,8 @@ SequenceTypeTests.test("starts(with:)/WhereElementIsEquatable") { } } -SequenceTypeTests.test("starts(with:)/Predicate") { - for test in startsWithTests { +SequenceTypeTests.test("hasPrefix(_:)/Predicate") { + for test in hasPrefixTests { do { let s = MinimalSequence>( elements: test.sequence.map(OpaqueValue.init)) @@ -325,7 +325,7 @@ SequenceTypeTests.test("starts(with:)/Predicate") { elements: test.prefix.map(OpaqueValue.init)) expectEqual( test.expected, - s.starts(with: prefix) { $0.value == $1.value }, + s.hasPrefix(prefix) { $0.value == $1.value }, stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.expectedLeftoverSequence, s.map { $0.value }, @@ -341,7 +341,7 @@ SequenceTypeTests.test("starts(with:)/Predicate") { elements: test.prefix.map(OpaqueValue.init)) expectEqual( test.expected, - s.starts(with: prefix) { $0.value / 2 == $1.value }, + s.hasPrefix(prefix) { $0.value / 2 == $1.value }, stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.expectedLeftoverSequence, s.map { $0.value / 2 }, @@ -359,7 +359,7 @@ SequenceTypeTests.test("starts(with:)/Predicate") { elements: test.prefix.map(OpaqueValue.init)) expectEqual( test.expected, - s.starts(with: prefix) { $0.value == $1.value }, + s.hasPrefix(prefix) { $0.value == $1.value }, stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.sequence, s.map { $0.value }, @@ -943,33 +943,33 @@ SequenceTypeTests.test("forEach/dispatch") { } //===----------------------------------------------------------------------===// -// dropFirst() +// removingPrefix() //===----------------------------------------------------------------------===// -SequenceTypeTests.test("dropFirst/dispatch") { +SequenceTypeTests.test("removingPrefix/dispatch") { var tester = SequenceLog.dispatchTester([OpaqueValue(1)]) - _ = tester.dropFirst(1) - expectCustomizable(tester, tester.log.dropFirst) + _ = tester.removingPrefix(1) + expectCustomizable(tester, tester.log.removingPrefix) } //===----------------------------------------------------------------------===// -// dropLast() +// removingSuffix() //===----------------------------------------------------------------------===// -SequenceTypeTests.test("dropLast/dispatch") { +SequenceTypeTests.test("removingSuffix/dispatch") { var tester = SequenceLog.dispatchTester([OpaqueValue(1)]) - _ = tester.dropLast(1) - expectCustomizable(tester, tester.log.dropLast) + _ = tester.removingSuffix(1) + expectCustomizable(tester, tester.log.removingSuffix) } //===----------------------------------------------------------------------===// -// drop(while:) +// removingPrefix(while:) //===----------------------------------------------------------------------===// -SequenceTypeTests.test("drop(while:)/dispatch") { +SequenceTypeTests.test("removingPrefix(while:)/dispatch") { var tester = SequenceLog.dispatchTester([OpaqueValue(1)]) - tester.drop { _ in return false } - expectCustomizable(tester, tester.log.dropWhile) + tester.removingPrefix { _ in return false } + expectCustomizable(tester, tester.log.removingPrefixWhile) } //===----------------------------------------------------------------------===// @@ -982,9 +982,9 @@ SequenceTypeTests.test("prefix/dispatch") { expectCustomizable(tester, tester.log.prefixMaxLength) } -SequenceTypeTests.test("prefix/drop/dispatch") { +SequenceTypeTests.test("prefix/removingPrefix/dispatch") { let xs = sequence(first: 1, next: {$0 < 10 ? $0 + 1 : nil}) - expectEqualSequence([], Array(xs.prefix(3).drop(while: {$0 < 7}))) + expectEqualSequence([], Array(xs.prefix(3).removingPrefix(while: {$0 < 7}))) } //===----------------------------------------------------------------------===// diff --git a/validation-test/stdlib/Set.swift b/validation-test/stdlib/Set.swift index b40979604bb59..f59ddd35660dc 100644 --- a/validation-test/stdlib/Set.swift +++ b/validation-test/stdlib/Set.swift @@ -598,10 +598,10 @@ SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") { // Find an existing key. do { - var foundIndex1 = s.index(of: 1010)! + var foundIndex1 = s.firstIndex(of: 1010)! expectEqual(identity1, s._rawIdentifier()) - var foundIndex2 = s.index(of: 1010)! + var foundIndex2 = s.firstIndex(of: 1010)! expectEqual(foundIndex1, foundIndex2) expectEqual(1010, s[foundIndex1]) @@ -610,7 +610,7 @@ SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") { // Try to find a key that is not present. do { - var foundIndex1 = s.index(of: 1111) + var foundIndex1 = s.firstIndex(of: 1111) expectNil(foundIndex1) expectEqual(identity1, s._rawIdentifier()) } @@ -619,7 +619,7 @@ SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") { var s2: Set = [] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 - expectNil(s2.index(of: MinimalHashableValue(42))) + expectNil(s2.firstIndex(of: MinimalHashableValue(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. @@ -634,10 +634,10 @@ SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") { // Find an existing key. do { - var foundIndex1 = s.index(of: TestKeyTy(1010))! + var foundIndex1 = s.firstIndex(of: TestKeyTy(1010))! expectEqual(identity1, s._rawIdentifier()) - var foundIndex2 = s.index(of: TestKeyTy(1010))! + var foundIndex2 = s.firstIndex(of: TestKeyTy(1010))! expectEqual(foundIndex1, foundIndex2) expectEqual(TestKeyTy(1010), s[foundIndex1]) @@ -646,7 +646,7 @@ SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") { // Try to find a key that is not present. do { - var foundIndex1 = s.index(of: TestKeyTy(1111)) + var foundIndex1 = s.firstIndex(of: TestKeyTy(1111)) expectNil(foundIndex1) expectEqual(identity1, s._rawIdentifier()) } @@ -655,7 +655,7 @@ SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") { var s2: Set = [] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 - expectNil(s2.index(of: MinimalHashableClass(42))) + expectNil(s2.firstIndex(of: MinimalHashableClass(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. @@ -672,7 +672,7 @@ SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") var s = getCOWFastSet() var identity1 = s._rawIdentifier() - let foundIndex1 = s.index(of: 1010)! + let foundIndex1 = s.firstIndex(of: 1010)! expectEqual(identity1, s._rawIdentifier()) expectEqual(1010, s[foundIndex1]) @@ -681,7 +681,7 @@ SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") expectEqual(1010, removed) expectEqual(identity1, s._rawIdentifier()) - expectNil(s.index(of: 1010)) + expectNil(s.firstIndex(of: 1010)) } do { @@ -692,7 +692,7 @@ SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) - var foundIndex1 = s2.index(of: 1010)! + var foundIndex1 = s2.firstIndex(of: 1010)! expectEqual(1010, s2[foundIndex1]) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) @@ -702,7 +702,7 @@ SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) - expectNil(s2.index(of: 1010)) + expectNil(s2.firstIndex(of: 1010)) } } @@ -714,7 +714,7 @@ SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") var s = getCOWSlowSet() var identity1 = s._rawIdentifier() - let foundIndex1 = s.index(of: TestKeyTy(1010))! + let foundIndex1 = s.firstIndex(of: TestKeyTy(1010))! expectEqual(identity1, s._rawIdentifier()) expectEqual(TestKeyTy(1010), s[foundIndex1]) @@ -723,7 +723,7 @@ SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") expectEqual(TestKeyTy(1010), removed) expectEqual(identity1, s._rawIdentifier()) - expectNil(s.index(of: TestKeyTy(1010))) + expectNil(s.firstIndex(of: TestKeyTy(1010))) } do { @@ -734,7 +734,7 @@ SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) - var foundIndex1 = s2.index(of: TestKeyTy(1010))! + var foundIndex1 = s2.firstIndex(of: TestKeyTy(1010))! expectEqual(TestKeyTy(1010), s2[foundIndex1]) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) @@ -744,7 +744,7 @@ SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) - expectNil(s2.index(of: TestKeyTy(1010))) + expectNil(s2.firstIndex(of: TestKeyTy(1010))) } } @@ -1361,17 +1361,17 @@ SetTestSuite.test("BridgedFromObjC.Verbatim.IndexForMember") { expectTrue(isCocoaSet(s)) // Find an existing key. - var member = s[s.index(of: TestObjCKeyTy(1010))!] + var member = s[s.firstIndex(of: TestObjCKeyTy(1010))!] expectEqual(TestObjCKeyTy(1010), member) - member = s[s.index(of: TestObjCKeyTy(2020))!] + member = s[s.firstIndex(of: TestObjCKeyTy(2020))!] expectEqual(TestObjCKeyTy(2020), member) - member = s[s.index(of: TestObjCKeyTy(3030))!] + member = s[s.firstIndex(of: TestObjCKeyTy(3030))!] expectEqual(TestObjCKeyTy(3030), member) // Try to find a key that does not exist. - expectNil(s.index(of: TestObjCKeyTy(4040))) + expectNil(s.firstIndex(of: TestObjCKeyTy(4040))) expectEqual(identity1, s._rawIdentifier()) } @@ -1380,17 +1380,17 @@ SetTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForMember") { var identity1 = s._rawIdentifier() do { - var member = s[s.index(of: TestBridgedKeyTy(1010))!] + var member = s[s.firstIndex(of: TestBridgedKeyTy(1010))!] expectEqual(TestBridgedKeyTy(1010), member) - member = s[s.index(of: TestBridgedKeyTy(2020))!] + member = s[s.firstIndex(of: TestBridgedKeyTy(2020))!] expectEqual(TestBridgedKeyTy(2020), member) - member = s[s.index(of: TestBridgedKeyTy(3030))!] + member = s[s.firstIndex(of: TestBridgedKeyTy(3030))!] expectEqual(TestBridgedKeyTy(3030), member) } - expectNil(s.index(of: TestBridgedKeyTy(4040))) + expectNil(s.firstIndex(of: TestBridgedKeyTy(4040))) expectEqual(identity1, s._rawIdentifier()) } @@ -1650,7 +1650,7 @@ SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { let identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) - let foundIndex1 = s.index(of: TestObjCKeyTy(1010))! + let foundIndex1 = s.firstIndex(of: TestObjCKeyTy(1010))! expectEqual(TestObjCKeyTy(1010), s[foundIndex1]) expectEqual(identity1, s._rawIdentifier()) @@ -1659,7 +1659,7 @@ SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { expectTrue(isNativeSet(s)) expectEqual(2, s.count) expectEqual(TestObjCKeyTy(1010), removedElement) - expectNil(s.index(of: TestObjCKeyTy(1010))) + expectNil(s.firstIndex(of: TestObjCKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") @@ -1670,7 +1670,7 @@ SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") let identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) - let foundIndex1 = s.index(of: TestBridgedKeyTy(1010))! + let foundIndex1 = s.firstIndex(of: TestBridgedKeyTy(1010))! expectEqual(1010, s[foundIndex1].value) expectEqual(identity1, s._rawIdentifier()) @@ -1679,7 +1679,7 @@ SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") expectTrue(isNativeSet(s)) expectEqual(1010, removedElement.value) expectEqual(2, s.count) - expectNil(s.index(of: TestBridgedKeyTy(1010))) + expectNil(s.firstIndex(of: TestBridgedKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Verbatim.Remove") { @@ -3162,7 +3162,7 @@ SetTestSuite.test("contains") { SetTestSuite.test("memberAtIndex") { let s1 = Set([1010, 2020, 3030]) - let foundIndex = s1.index(of: 1010)! + let foundIndex = s1.firstIndex(of: 1010)! expectEqual(1010, s1[foundIndex]) } @@ -3313,12 +3313,12 @@ SetTestSuite.test("_customContainsEquatableElement") { expectFalse(Set()._customContainsEquatableElement(1010)!) } -SetTestSuite.test("index(of:)") { +SetTestSuite.test("firstIndex(of:)") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) - let foundIndex1 = s1.index(of: 1010)! + let foundIndex1 = s1.firstIndex(of: 1010)! expectEqual(1010, s1[foundIndex1]) - expectNil(s1.index(of: 999)) + expectNil(s1.firstIndex(of: 999)) } SetTestSuite.test("popFirst") { @@ -3346,10 +3346,10 @@ SetTestSuite.test("removeAt") { // Test removing from the startIndex, the middle, and the end of a set. for i in 1...3 { var s = Set([1010, 2020, 3030]) - let removed = s.remove(at: s.index(of: i*1010)!) + let removed = s.remove(at: s.firstIndex(of: i*1010)!) expectEqual(i*1010, removed) expectEqual(2, s.count) - expectNil(s.index(of: i*1010)) + expectNil(s.firstIndex(of: i*1010)) let origKeys: [Int] = [1010, 2020, 3030] expectEqual(origKeys.filter { $0 != (i*1010) }, [Int](s).sorted()) } diff --git a/validation-test/stdlib/SetAnyHashableExtensions.swift b/validation-test/stdlib/SetAnyHashableExtensions.swift index 3b53df3a571e1..3ab8cea2682f9 100644 --- a/validation-test/stdlib/SetAnyHashableExtensions.swift +++ b/validation-test/stdlib/SetAnyHashableExtensions.swift @@ -43,13 +43,13 @@ SetTests.test("index(of:)") { let s: Set = [ AnyHashable(1010), AnyHashable(2020), AnyHashable(3030.0) ] - expectEqual(AnyHashable(1010), s[s.index(of: 1010)!]) - expectEqual(AnyHashable(2020), s[s.index(of: 2020)!]) - expectEqual(AnyHashable(3030.0), s[s.index(of: 3030.0)!]) + expectEqual(AnyHashable(1010), s[s.firstIndex(of: 1010)!]) + expectEqual(AnyHashable(2020), s[s.firstIndex(of: 2020)!]) + expectEqual(AnyHashable(3030.0), s[s.firstIndex(of: 3030.0)!]) - expectNil(s.index(of: 1010.0)) - expectNil(s.index(of: 2020.0)) - expectNil(s.index(of: 3030)) + expectNil(s.firstIndex(of: 1010.0)) + expectNil(s.firstIndex(of: 2020.0)) + expectNil(s.firstIndex(of: 3030)) } SetTests.test("insert(_:)") { diff --git a/validation-test/stdlib/StringHashableComparable.swift.gyb b/validation-test/stdlib/StringHashableComparable.swift.gyb index bb4893ccecf6b..a8cc244387a22 100644 --- a/validation-test/stdlib/StringHashableComparable.swift.gyb +++ b/validation-test/stdlib/StringHashableComparable.swift.gyb @@ -36,7 +36,7 @@ func calculateSortOrder(_ tests: inout [StringComparisonTest]) { } tests[0].order = 0 - for i in tests.indices.dropFirst() { + for i in tests.indices.removingFirst() { if collationElements( tests[i - 1].collationElements, areLessThan: tests[i].collationElements