Skip to content

Commit 7a2f5df

Browse files
author
Alexander Schmutz
committed
Exclude constant variables from struct members
1 parent 8e3f6c4 commit 7a2f5df

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

Sources/StructBuilderClient/main.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,9 @@ class MyClass {
5050
self.m1 = m1
5151
}
5252
}
53+
54+
@Buildable
55+
struct MyStruct {
56+
let m1: String
57+
let fix: String = ""
58+
}

Sources/StructBuilderMacro/StructAndClass/Helper/ExtractMembers.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ func extractMembersFrom(_ memberBlockItemList: MemberBlockItemListSyntax) -> [St
1313
.filter(\.isStoredProperty)
1414
.filter { !hasStaticModifier($0) }
1515
.filter { !hasPrivateModifier($0) }
16+
.filter { !isConstant($0) }
1617
.compactMap {
1718
guard let patternBinding = $0.bindings.first else { return nil }
1819
guard let identifier = getIdentifierFromMember(patternBinding) else { return nil }
@@ -37,6 +38,11 @@ private func hasPrivateModifier(_ variable: VariableDeclSyntax) -> Bool {
3738
variable.modifiers.contains(where: { $0.name.text.contains("private") })
3839
}
3940

41+
private func isConstant(_ variable: VariableDeclSyntax) -> Bool {
42+
variable.bindingSpecifier.text == "let"
43+
&& variable.bindings.first?.initializer != nil
44+
}
45+
4046
// SOURCE: https://github.com/apple/swift-syntax/tree/main/Examples
4147
private extension VariableDeclSyntax {
4248
/// Determine whether this variable has the syntax of a stored property.

Tests/StructBuilderMacroTests/BuildableStructTests.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,36 @@ class BuildableStructTests: XCTestCase {
285285
)
286286
}
287287

288+
func test_should_ignore_constant_variables() {
289+
assertMacroExpansion(
290+
"""
291+
@Buildable
292+
struct MyObject {
293+
let m1: String?
294+
let myConstant: String = ""
295+
}
296+
""",
297+
expandedSource: """
298+
299+
struct MyObject {
300+
let m1: String?
301+
let myConstant: String = ""
302+
}
303+
304+
struct MyObjectBuilder {
305+
var m1: String?
306+
307+
func build() -> MyObject {
308+
return MyObject(
309+
m1: m1
310+
)
311+
}
312+
}
313+
""",
314+
macros: testMacros
315+
)
316+
}
317+
288318
func test_should_set_correct_default_values_for_defined_types() {
289319
assertMacroExpansion(
290320
"""

0 commit comments

Comments
 (0)