Skip to content

Add AnyRegexOutput.as(_:). #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Sources/_StringProcessing/RegexDSL/AnyRegexOutput.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ extension AnyRegexOutput {
fatalError("FIXME: Not implemented")
// self.init(input: match.input, _elements: <elements of output tuple>)
}

/// Returns a typed output by converting the underlying value to the specified
/// type.
/// - Parameter type: The expected output type.
/// - Returns: The output, if the underlying value can be converted to the
/// output type, or nil otherwise.
public func `as`<Output>(_ type: Output.Type) -> Output? {
let elements = _elements.map {
StructuredCapture(
optionalCount: $0.optionalDepth,
storedCapture: .init(range: $0.bounds)
).existentialOutputComponent(from: input[...])
}
return TypeConstruction.tuple(of: elements) as? Output
}
}

extension AnyRegexOutput {
Expand Down
6 changes: 6 additions & 0 deletions Tests/RegexTests/RegexDSLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,12 @@ class RegexDSLTests: XCTestCase {
XCTAssertTrue(output[1].substring == "A6F0")
XCTAssertTrue(output[2].substring == "A6F1")
XCTAssertTrue(output[3].substring == "Extend")
let typedOutput = try XCTUnwrap(output.as(
(Substring, Substring, Substring?, Substring).self))
XCTAssertEqual(typedOutput.0, line[...])
XCTAssertTrue(typedOutput.1 == "A6F0")
XCTAssertTrue(typedOutput.2 == "A6F1")
XCTAssertTrue(typedOutput.3 == "Extend")
}
}

Expand Down