Skip to content

Commit c22a9a8

Browse files
committed
[Syntax] Provide a Syntax constructor that can accept an optional parameter
Also add test to ensure the casting to `SyntaxEnum` via optional chaining works as expected.
1 parent 946caf4 commit c22a9a8

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

Sources/SwiftSyntax/Syntax.swift

+6
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable {
3434
self = syntax._syntaxNode
3535
}
3636

37+
/// Create a `Syntax` node from a specialized optional syntax node.
38+
public init?<S: SyntaxProtocol>(_ syntax: S?) {
39+
guard let syntax = syntax else { return nil }
40+
self = syntax._syntaxNode
41+
}
42+
3743
public func hash(into hasher: inout Hasher) {
3844
return data.nodeId.hash(into: &hasher)
3945
}

Tests/SwiftSyntaxTest/SyntaxTests.swift

+6
Original file line numberDiff line numberDiff line change
@@ -113,5 +113,11 @@ public class SyntaxTests: XCTestCase {
113113

114114
XCTAssertTrue(classDecl.is(BracedSyntax.self))
115115
XCTAssertNotNil(classDecl.as(BracedSyntax.self))
116+
117+
let optNode: Syntax? = node
118+
switch optNode?.as(SyntaxEnum.self) {
119+
case .integerLiteralExpr: break
120+
default: XCTFail("failed to convert to SyntaxEnum")
121+
}
116122
}
117123
}

0 commit comments

Comments
 (0)