diff --git a/Sources/Rules.swift b/Sources/Rules.swift index 62dde1b61..03abcc67c 100644 --- a/Sources/Rules.swift +++ b/Sources/Rules.swift @@ -2956,7 +2956,8 @@ public struct _FormatRules { if formatter.index(of: .endOfStatement, in: index + 1 ..< optionalIndex) != nil { return } - if !formatter.tokens[optionalIndex - 1].isSpaceOrCommentOrLinebreak { + let previousToken = formatter.tokens[optionalIndex - 1] + if !previousToken.isSpaceOrCommentOrLinebreak && previousToken != .keyword("as") { let equalsIndex = formatter.index(of: .nonSpaceOrLinebreak, after: optionalIndex, if: { $0 == .operator("=", .infix) }) diff --git a/Tests/RulesTests+Redundancy.swift b/Tests/RulesTests+Redundancy.swift index c8081cb49..29d9236cc 100644 --- a/Tests/RulesTests+Redundancy.swift +++ b/Tests/RulesTests+Redundancy.swift @@ -2266,6 +2266,16 @@ class RedundancyTests: RulesTests { options: options) } + func testNoInsertNilInitInAs() { + let input = """ + let json: Any = ["key": 1] + var jsonObject = json as? [String: Int] + """ + let options = FormatOptions(nilInit: .insert) + testFormatting(for: input, rule: FormatRules.redundantNilInit, + options: options) + } + // MARK: - redundantLet func testRemoveRedundantLet() {