Skip to content

Commit 175df29

Browse files
caldanicklockwood
authored andcommitted
Fix issue where forEach with 'guard ... else { return }' would be preserved unnecessarily
1 parent 4c73305 commit 175df29

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

Sources/Rules.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7839,13 +7839,13 @@ public struct _FormatRules {
78397839
return
78407840
}
78417841

7842-
// We can convert `return`s to `continue`, but only when `return` is on its own line.
7842+
// We can convert `return`s to `continue`, but only when `return` is the last token in the scope.
78437843
// It's legal to write something like `return print("foo")` in a `forEach` as long as
78447844
// you're still returning a `Void` value. Since `continue print("foo")` isn't legal,
78457845
// we should just ignore this closure.
78467846
if formatter.tokens[closureBodyIndex] == .keyword("return"),
78477847
let tokenAfterReturnKeyword = formatter.next(.nonSpaceOrComment, after: closureBodyIndex),
7848-
!tokenAfterReturnKeyword.isLinebreak
7848+
!(tokenAfterReturnKeyword.isLinebreak || tokenAfterReturnKeyword == .endOfScope("}"))
78497849
{
78507850
return
78517851
}

Tests/RulesTests+Syntax.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4959,4 +4959,23 @@ class SyntaxTests: RulesTests {
49594959

49604960
testFormatting(for: input, output, rule: FormatRules.preferForLoop)
49614961
}
4962+
4963+
func testConvertsForEachWithGuardElseReturn() {
4964+
let input = """
4965+
strings.forEach { string in
4966+
guard !string.isEmpty else { return }
4967+
print(string)
4968+
}
4969+
"""
4970+
4971+
let output = """
4972+
for string in strings {
4973+
guard !string.isEmpty else { continue }
4974+
print(string)
4975+
}
4976+
"""
4977+
4978+
testFormatting(for: input, output, rule: FormatRules.preferForLoop,
4979+
exclude: ["wrapConditionalBodies"])
4980+
}
49624981
}

0 commit comments

Comments
 (0)