diff --git a/Sources/Rules/RedundantInit.swift b/Sources/Rules/RedundantInit.swift index 0df3f135..0b717779 100644 --- a/Sources/Rules/RedundantInit.swift +++ b/Sources/Rules/RedundantInit.swift @@ -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 diff --git a/Tests/Rules/RedundantInitTests.swift b/Tests/Rules/RedundantInitTests.swift index 4d7b88ea..4990065c 100644 --- a/Tests/Rules/RedundantInitTests.swift +++ b/Tests/Rules/RedundantInitTests.swift @@ -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]) + } }