Skip to content

Commit

Permalink
Fix redundantClosure inside conditional statement
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Oct 24, 2023
1 parent 0aabc4d commit 5461f51
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
15 changes: 15 additions & 0 deletions Tests/RulesTests+Redundancy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 5461f51

Please sign in to comment.