From 5461f5145561e51dcd12caf5bf03e5d8b78c6ad7 Mon Sep 17 00:00:00 2001 From: Nick Lockwood Date: Tue, 24 Oct 2023 06:48:26 -0700 Subject: [PATCH] Fix `redundantClosure` inside conditional statement --- Sources/Rules.swift | 5 +++++ Tests/RulesTests+Redundancy.swift | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Sources/Rules.swift b/Sources/Rules.swift index 1d82c867e..f8660eb84 100644 --- a/Sources/Rules.swift +++ b/Sources/Rules.swift @@ -6261,6 +6261,11 @@ public struct _FormatRules { var startOfScopeContainingClosure = formatter.startOfScope(at: startIndex) var assignmentBeforeClosure = formatter.index(of: .operator("=", .infix), before: startIndex) + if let assignmentBeforeClosure = assignmentBeforeClosure, formatter.isConditionalStatement(at: assignmentBeforeClosure) { + // Not valid to use conditional expression directly in condition body + return + } + let potentialStartOfExpressionContainingClosure: Int? switch (startOfScopeContainingClosure, assignmentBeforeClosure) { case (nil, nil): diff --git a/Tests/RulesTests+Redundancy.swift b/Tests/RulesTests+Redundancy.swift index 8a8b71a4d..3ef6a81c9 100644 --- a/Tests/RulesTests+Redundancy.swift +++ b/Tests/RulesTests+Redundancy.swift @@ -8470,6 +8470,21 @@ class RedundancyTests: RulesTests { testFormatting(for: input, output, rule: FormatRules.redundantClosure, options: options, exclude: ["indent"]) } + func testClosureNotRemovedAroundIfExpressionInGuard() { + let input = """ + guard let foo = { + if condition { + bar() + } + }() else { + return + } + """ + + let options = FormatOptions(swiftVersion: "5.9") + testFormatting(for: input, rule: FormatRules.redundantClosure, options: options) + } + // MARK: Redundant optional binding func testRemovesRedundantOptionalBindingsInSwift5_7() {