Skip to content

Commit 7ac5318

Browse files
authored
Merge pull request swiftlang#139 from google/fix-casts
Fix force cast rule to only fire on "as!".
2 parents 3ba04b7 + 8f62bcd commit 7ac5318

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

Sources/SwiftFormatRules/NeverForceUnwrap.swift

+6-1
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ import SwiftSyntax
2323
/// - SeeAlso: https://google.github.io/swift#force-unwrapping-and-force-casts
2424
public final class NeverForceUnwrap: SyntaxLintRule {
2525

26-
// Checks if "XCTest" is an import statement
2726
public override func visit(_ node: SourceFileSyntax) {
27+
// Tracks whether "XCTest" is imported in the source file before processing the individual
2828
setImportsXCTest(context: context, sourceFile: node)
2929
super.visit(node)
3030
}
@@ -35,7 +35,11 @@ public final class NeverForceUnwrap: SyntaxLintRule {
3535
}
3636

3737
public override func visit(_ node: AsExprSyntax) {
38+
// Only fire if we're not in a test file and if there is an exclamation mark following the `as`
39+
// keyword.
3840
guard !context.importsXCTest else { return }
41+
guard let questionOrExclamation = node.questionOrExclamationMark else { return }
42+
guard questionOrExclamation.tokenKind == .exclamationMark else { return }
3943
diagnose(.doNotForceCast(name: node.typeName.description), on: node)
4044
}
4145
}
@@ -44,6 +48,7 @@ extension Diagnostic.Message {
4448
static func doNotForceUnwrap(name: String) -> Diagnostic.Message {
4549
return .init(.warning, "do not force unwrap '\(name)'")
4650
}
51+
4752
static func doNotForceCast(name: String) -> Diagnostic.Message {
4853
return .init(.warning, "do not force cast to '\(name)'")
4954
}

0 commit comments

Comments
 (0)