Fix redundantInit rule: preserve .init with trailing closure on collection types for Swift < 6.4 (#2396)

Co-authored-by: calda <1811727+calda@users.noreply.github.com>
This commit is contained in:
Copilot
2026-02-21 09:28:18 -08:00
committed by GitHub
parent babf646a3a
commit 190a3615f3
2 changed files with 46 additions and 0 deletions
+8
View File
@@ -46,6 +46,14 @@ public extension FormatRule {
if [.startOfScope("#if"), .keyword("#elseif")].contains(formatter.tokens[lineStart]) {
return
}
// In Swift < 6.4, trailing closure syntax is not allowed after array/dictionary
// literals (e.g. `[String] { "foo" }`). This was fixed in SE-0508 for Swift 6.4+.
if formatter.tokens[openParenOrOpenBraceIndex] == .startOfScope("{"),
prevToken == .endOfScope("]"),
formatter.options.swiftVersion < "6.4"
{
return
}
var j = dotIndex
while let prevIndex = formatter.index(
of: prevToken, before: j
+38
View File
@@ -295,4 +295,42 @@ final class RedundantInitTests: XCTestCase {
"""
testFormatting(for: input, output, rule: .redundantInit, exclude: [.propertyTypes])
}
func testPreserveInitOnCollectionTypeWithTrailingClosureBeforeSwift64() {
let input = """
[String].init { "foo" }
[String: Int].init { ("key", 1) }
[[String]].init { ["foo"] }
"""
let options = FormatOptions(swiftVersion: "6.3")
testFormatting(for: input, rule: .redundantInit, options: options)
}
func testRemoveInitOnCollectionTypeWithTrailingClosureInSwift64() {
let input = """
[String].init { "foo" }
[String: Int].init { ("key", 1) }
[[String]].init { ["foo"] }
"""
let output = """
[String] { "foo" }
[String: Int] { ("key", 1) }
[[String]] { ["foo"] }
"""
let options = FormatOptions(swiftVersion: "6.4")
testFormatting(for: input, output, rule: .redundantInit, options: options)
}
func testRemoveInitOnCollectionTypeWithParensUnaffectedBySwiftVersion() {
let input = """
let array = [String].init()
let dictionary = [String: Int].init()
"""
let output = """
let array = [String]()
let dictionary = [String: Int]()
"""
let options = FormatOptions(swiftVersion: "6.3")
testFormatting(for: input, output, rule: .redundantInit, options: options, exclude: [.propertyTypes])
}
}