Skip to content

Commit

Permalink
Don't trigger on if case statements
Browse files Browse the repository at this point in the history
  • Loading branch information
cmillani committed Aug 31, 2019
1 parent 899b38a commit 2336a5d
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -60,6 +60,9 @@
[Marcelo Fabri](https://github.com/marcelofabri)
[#2851](https://github.com/realm/SwiftLint/issues/2851)

* Don't trigger `explicit_type_interface` on `if case let` statements.
[Carlos Millani](https://github.com/cmillani)

## 0.34.0: Anti-Static Wool Dryer Balls

#### Breaking
Expand Down
2 changes: 1 addition & 1 deletion Source/SwiftLintFramework/Models/MasterRuleList.swift
@@ -1,4 +1,4 @@
// Generated using Sourcery 0.16.1 — https://github.com/krzysztofzablocki/Sourcery
// Generated using Sourcery 0.16.2 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT

public let masterRuleList = RuleList(rules: [
Expand Down
Expand Up @@ -95,6 +95,7 @@ public struct ExplicitTypeInterfaceRule: OptInRule, ConfigurationProviderRule {
(!configuration.allowRedundancy ||
(!dictionary.isInitCall(file: file) && !dictionary.isTypeReferenceAssignment(file: file))
),
!dictionary.isIfCaseCall(file: file, parentStructure: parentStructure),
!parentStructure.contains([.forEach, .guard]),
!parentStructure.caseStatementPatternRanges.contains(offset),
!parentStructure.caseExpressionRanges.contains(offset),
Expand All @@ -115,6 +116,20 @@ private extension Dictionary where Key == String, Value == SourceKitRepresentabl
return typeName != nil
}

func isIfCaseCall(file: File, parentStructure: [String: SourceKitRepresentable]) -> Bool {
guard parentStructure.kind == SwiftExpressionKind.call.rawValue,
let parentOffset = parentStructure.offset,
case let contents = file.contents.bridge(),
let beforeParentRange = contents.byteRangeToNSRange(start: parentOffset, length: 0) else {
return false
}

let fileUpToParent = contents.substring(to: beforeParentRange.location)
let isCaseRegex = regex("if\\s+case\\s+(let|var)?\\s*$")

return isCaseRegex.firstMatch(in: fileUpToParent, options: [], range: fileUpToParent.fullNSRange) != nil
}

func isInitCall(file: File) -> Bool {
guard
let nameOffset = nameOffset,
Expand Down
11 changes: 11 additions & 0 deletions Tests/SwiftLintFrameworkTests/ExplicitTypeInterfaceRuleTests.swift
Expand Up @@ -178,6 +178,17 @@ class ExplicitTypeInterfaceRuleTests: XCTestCase {
case var (x, y): break
}
}
""",
"""
enum Foo {
case caseOne(propOne: Int)
}
let testA: Foo = .caseOne(propOne: 2)
if case let Foo.caseOne(propOne) = testA { }
if case Foo.caseOne(let propOne) = testA { }
"""
]

Expand Down

0 comments on commit 2336a5d

Please sign in to comment.