Skip to content

Commit bef2092

Browse files
authored
Mention language level pattern matching (#354)
1 parent e0922ec commit bef2092

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Documentation/Evolution/StringProcessingAlgorithms.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,31 @@ We also propose the following regex-powered algorithms as well as their generic
166166
|`prefixMatch(of:)`| Matches the specified `RegexComponent` against the collection at the beginning |
167167
|`matches(of:)`| Returns a collection containing all matches of the specified `RegexComponent` |
168168

169+
We also propose an overload of `~=` allowing regexes to be used in `case` expressions:
170+
171+
```swift
172+
switch "abcde" {
173+
case /a.*f/: // never taken
174+
case /abc/: // never taken
175+
case /ab.*e/: return "success"
176+
default: // never taken
177+
}
178+
179+
switch "2022-04-22" {
180+
case decimalParser: // never taken
181+
182+
case OneOrMore {
183+
CharacterClass.whitespace
184+
}: // never taken
185+
186+
case #/\d{2}/\d{2}/\d{4}/# // never taken
187+
188+
case dateParser: return "success"
189+
190+
default: // never taken
191+
}
192+
```
193+
169194

170195
## Detailed design
171196

@@ -1025,6 +1050,19 @@ extension RangeReplaceableCollection where Element: Equatable {
10251050
}
10261051
```
10271052

1053+
### Language-level pattern matching via `~=`
1054+
1055+
We propose allowing any regex component be used in case statements by overloading the `~=` operator for matching against the entire input:
1056+
1057+
```swift
1058+
extension RegexComponent {
1059+
public static func ~=(regex: Self, input: String) -> Bool
1060+
1061+
public static func ~=(regex: Self, input: Substring) -> Bool
1062+
}
1063+
```
1064+
1065+
10281066
[SE-0346]: https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md
10291067
[stdlib-pitch]: https://forums.swift.org/t/pitch-primary-associated-types-in-the-standard-library/56426
10301068

Tests/RegexBuilderTests/AlgorithmsTests.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ class RegexConsumerTests: XCTestCase {
116116
}:
117117
XCTFail()
118118

119+
case OneOrMore { CharacterClass.whitespace }:
120+
XCTFail()
121+
119122
case "abc":
120123
XCTFail()
121124

0 commit comments

Comments
 (0)