Skip to content

Commit

Permalink
Fix issue where forEach with 'guard ... else { return }' would be pre…
Browse files Browse the repository at this point in the history
…served unnecessarily
  • Loading branch information
calda authored and nicklockwood committed Sep 11, 2024
1 parent 4c73305 commit 175df29
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7839,13 +7839,13 @@ public struct _FormatRules {
return
}

// We can convert `return`s to `continue`, but only when `return` is on its own line.
// We can convert `return`s to `continue`, but only when `return` is the last token in the scope.
// It's legal to write something like `return print("foo")` in a `forEach` as long as
// you're still returning a `Void` value. Since `continue print("foo")` isn't legal,
// we should just ignore this closure.
if formatter.tokens[closureBodyIndex] == .keyword("return"),
let tokenAfterReturnKeyword = formatter.next(.nonSpaceOrComment, after: closureBodyIndex),
!tokenAfterReturnKeyword.isLinebreak
!(tokenAfterReturnKeyword.isLinebreak || tokenAfterReturnKeyword == .endOfScope("}"))
{
return
}
Expand Down
19 changes: 19 additions & 0 deletions Tests/RulesTests+Syntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4959,4 +4959,23 @@ class SyntaxTests: RulesTests {

testFormatting(for: input, output, rule: FormatRules.preferForLoop)
}

func testConvertsForEachWithGuardElseReturn() {
let input = """
strings.forEach { string in
guard !string.isEmpty else { return }
print(string)
}
"""

let output = """
for string in strings {
guard !string.isEmpty else { continue }
print(string)
}
"""

testFormatting(for: input, output, rule: FormatRules.preferForLoop,
exclude: ["wrapConditionalBodies"])
}
}

0 comments on commit 175df29

Please sign in to comment.