Skip to content

Commit f20e24b

Browse files
committed
Add AnyRegexOutput.as(_:).
Supports conversion from `AnyRegexOutput` to a user-specified type.
1 parent f00bfe0 commit f20e24b

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Sources/_StringProcessing/RegexDSL/AnyRegexOutput.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,21 @@ extension AnyRegexOutput {
5656
fatalError("FIXME: Not implemented")
5757
// self.init(input: match.input, _elements: <elements of output tuple>)
5858
}
59+
60+
/// Returns a typed output by converting the underlying value to the specified
61+
/// type.
62+
/// - Parameter type: The expected output type.
63+
/// - Returns: The output, if the underlying value can be converted to the
64+
/// output type, or nil otherwise.
65+
public func `as`<Output>(_ type: Output.Type) -> Output? {
66+
let elements = _elements.map {
67+
StructuredCapture(
68+
optionalCount: $0.optionalDepth,
69+
storedCapture: .init(range: $0.bounds)
70+
).existentialOutputComponent(from: input[...])
71+
}
72+
return TypeConstruction.tuple(of: elements) as? Output
73+
}
5974
}
6075

6176
extension AnyRegexOutput {

Tests/RegexTests/RegexDSLTests.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,12 @@ class RegexDSLTests: XCTestCase {
572572
XCTAssertTrue(output[1].substring == "A6F0")
573573
XCTAssertTrue(output[2].substring == "A6F1")
574574
XCTAssertTrue(output[3].substring == "Extend")
575+
let typedOutput = try XCTUnwrap(output.as(
576+
(Substring, Substring, Substring?, Substring).self))
577+
XCTAssertEqual(typedOutput.0, line[...])
578+
XCTAssertTrue(typedOutput.1 == "A6F0")
579+
XCTAssertTrue(typedOutput.2 == "A6F1")
580+
XCTAssertTrue(typedOutput.3 == "Extend")
575581
}
576582
}
577583

0 commit comments

Comments
 (0)