From 92b4e7df144a33aef32e62bad9498d199ce827da Mon Sep 17 00:00:00 2001 From: Nick Lockwood Date: Wed, 1 Mar 2023 19:02:25 +0000 Subject: [PATCH] Fix `redundantNilInit` removing required `nil` inside ViewBuilder --- Sources/Rules.swift | 2 +- Tests/RulesTests+Redundancy.swift | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Sources/Rules.swift b/Sources/Rules.swift index d752cd5e..af42db8f 100644 --- a/Sources/Rules.swift +++ b/Sources/Rules.swift @@ -2852,7 +2852,7 @@ public struct _FormatRules { formatter.forEach(.keyword("var")) { i, _ in if formatter.modifiersForDeclaration(at: i, contains: { $1 == "lazy" || ($1 != "@objc" && $1.hasPrefix("@")) - }) { + }) || formatter.isInResultBuilder(at: i) { return // Can't remove the init } // Check this isn't a Codable diff --git a/Tests/RulesTests+Redundancy.swift b/Tests/RulesTests+Redundancy.swift index 292d5341..235332d5 100644 --- a/Tests/RulesTests+Redundancy.swift +++ b/Tests/RulesTests+Redundancy.swift @@ -1772,6 +1772,51 @@ class RedundancyTests: RulesTests { testFormatting(for: input, output, rule: FormatRules.redundantNilInit) } + func testNoRemoveNilInitInViewBuilder() { + let input = """ + struct TestView: View { + var body: some View { + var foo: String? = nil + Text(foo ?? "") + } + } + """ + testFormatting(for: input, rule: FormatRules.redundantNilInit) + } + + func testNoRemoveNilInitInIfStatementInViewBuilder() { + let input = """ + struct TestView: View { + var body: some View { + if true { + var foo: String? + Text(foo ?? "") + } else { + EmptyView() + } + } + } + """ + testFormatting(for: input, rule: FormatRules.redundantNilInit) + } + + func testNoRemoveNilInitInSwitchStatementInViewBuilder() { + let input = """ + struct TestView: View { + var body: some View { + switch foo { + case .bar: + var foo: String? + Text(foo ?? "") + default: + EmptyView() + } + } + } + """ + testFormatting(for: input, rule: FormatRules.redundantNilInit) + } + // MARK: - redundantLet func testRemoveRedundantLet() {