From 4fd7bb0cbb2827ba7bcae0bfe8d98bc91ddde6e4 Mon Sep 17 00:00:00 2001 From: Nick Lockwood Date: Sun, 24 Nov 2024 08:21:10 +0000 Subject: [PATCH] Allow `.self` in keypaths --- Sources/Rules/PreferKeyPath.swift | 6 +++--- Tests/Rules/PreferKeyPathTests.swift | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Sources/Rules/PreferKeyPath.swift b/Sources/Rules/PreferKeyPath.swift index 455a53c8..96a9402e 100644 --- a/Sources/Rules/PreferKeyPath.swift +++ b/Sources/Rules/PreferKeyPath.swift @@ -57,9 +57,9 @@ public extension FormatRule { } var replacementTokens: [Token] if nextIndex == lastIndex { - // TODO: add this when https://bugs.swift.org/browse/SR-12897 is fixed - // replacementTokens = tokenize("\\.self") - return + // https://bugs.swift.org/browse/SR-12897 + guard formatter.options.swiftVersion >= "5.10" else { return } + replacementTokens = tokenize("\\.self") } else { let tokens = formatter.tokens[nextIndex + 1 ... lastIndex] guard tokens.allSatisfy({ $0.isSpace || $0.isIdentifier || $0.isOperator(".") }) else { diff --git a/Tests/Rules/PreferKeyPathTests.swift b/Tests/Rules/PreferKeyPathTests.swift index 54abad1e..9c1f4f7b 100644 --- a/Tests/Rules/PreferKeyPathTests.swift +++ b/Tests/Rules/PreferKeyPathTests.swift @@ -110,4 +110,18 @@ class PreferKeyPathTests: XCTestCase { let options = FormatOptions(swiftVersion: "5.2") testFormatting(for: input, rule: .preferKeyPath, options: options) } + + func testSelfNotConvertedToKeyPathBefore5_10() { + // https://bugs.swift.org/browse/SR-12897 + let input = "let foo = bar.compactMap { $0 }" + let options = FormatOptions(swiftVersion: "5.2") + testFormatting(for: input, rule: .preferKeyPath, options: options) + } + + func testSelfConvertedToKeyPath() { + let input = "let foo = bar.compactMap { $0 }" + let output = "let foo = bar.compactMap(\\.self)" + let options = FormatOptions(swiftVersion: "5.10") + testFormatting(for: input, output, rule: .preferKeyPath, options: options) + } }