Skip to content

Commit 70e4f96

Browse files
authored
Merge pull request #613 from fwcd/variable-decl-computed-init
Add convenience initializer for computed properties
2 parents 71f1af4 + 23a0106 commit 70e4f96

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Sources/SwiftSyntaxBuilder/VariableDeclConvenienceInitializers.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import SwiftSyntax
1414

1515
extension VariableDecl {
16+
/// Creates an optionally initialized property.
1617
public init(
1718
leadingTrivia: Trivia = [],
1819
_ letOrVarKeyword: TokenSyntax,
@@ -28,4 +29,21 @@ extension VariableDecl {
2829
)
2930
}
3031
}
32+
33+
/// Creates a computed property with the given accessor.
34+
public init(
35+
leadingTrivia: Trivia = [],
36+
modifiers: ModifierList? = nil,
37+
name: ExpressibleAsIdentifierPattern,
38+
type: ExpressibleAsTypeAnnotation,
39+
@CodeBlockItemListBuilder accessor: () -> ExpressibleAsCodeBlockItemList
40+
) {
41+
self.init(leadingTrivia: leadingTrivia, modifiers: modifiers, letOrVarKeyword: .var) {
42+
PatternBinding(
43+
pattern: name,
44+
typeAnnotation: type,
45+
accessor: CodeBlock(statements: accessor())
46+
)
47+
}
48+
}
3149
}

Tests/SwiftSyntaxBuilderTest/VariableTests.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,21 @@ final class VariableTests: XCTestCase {
8888
XCTAssertEqual(syntax.description, expected, line: line)
8989
}
9090
}
91+
92+
func testComputedProperty() {
93+
let buildable = VariableDecl(name: "test", type: "Int") {
94+
SequenceExpr {
95+
IntegerLiteralExpr(4)
96+
BinaryOperatorExpr("+")
97+
IntegerLiteralExpr(5)
98+
}
99+
}
100+
101+
let syntax = buildable.buildSyntax(format: Format())
102+
XCTAssertEqual(syntax.description, """
103+
var test: Int {
104+
4 + 5
105+
}
106+
""")
107+
}
91108
}

0 commit comments

Comments
 (0)