mirror of
https://github.com/nicklockwood/SwiftFormat.git
synced 2026-05-17 10:30:35 +00:00
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:
@@ -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
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user