diff --git a/CHANGELOG.md b/CHANGELOG.md index edb5be851a..1dff14ed73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,11 @@ [Timofey Solonin](https://github.com/biboran) [#2737](https://github.com/realm/SwiftLint/issues/2737) +* Avoid triggering `redundant_type_annotation` rule when declaring + `IBInspectable` properties. + [Marcelo Fabri](https://github.com/marcelofabri) + [#2842](https://github.com/realm/SwiftLint/issues/2842) + ## 0.34.0: Anti-Static Wool Dryer Balls #### Breaking diff --git a/Rules.md b/Rules.md index 8e8c896b10..cca238639f 100644 --- a/Rules.md +++ b/Rules.md @@ -17123,6 +17123,10 @@ var url = URL() var url: CustomStringConvertible = URL() ``` +```swift +@IBInspectable var color: UIColor = UIColor.white +``` +
Triggering Examples diff --git a/Source/SwiftLintFramework/Rules/Idiomatic/RedundantTypeAnnotationRule.swift b/Source/SwiftLintFramework/Rules/Idiomatic/RedundantTypeAnnotationRule.swift index df6da9ffea..592ed07474 100644 --- a/Source/SwiftLintFramework/Rules/Idiomatic/RedundantTypeAnnotationRule.swift +++ b/Source/SwiftLintFramework/Rules/Idiomatic/RedundantTypeAnnotationRule.swift @@ -14,7 +14,8 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul kind: .idiomatic, nonTriggeringExamples: [ "var url = URL()", - "var url: CustomStringConvertible = URL()" + "var url: CustomStringConvertible = URL()", + "@IBInspectable var color: UIColor = UIColor.white" ], triggeringExamples: [ "var url↓:URL=URL()", @@ -72,7 +73,7 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul let pattern = "(var|let)\\s?\\w+\(typeAnnotationPattern)\\s?=\\s?\\w+(\\(|.)" let foundRanges = file.match(pattern: pattern, with: [.keyword, .identifier, .typeidentifier, .identifier]) return foundRanges - .filter { !isFalsePositive(in: file, range: $0) } + .filter { !isFalsePositive(in: file, range: $0) && !isIBInspectable(range: $0, file: file) } .compactMap { file.match(pattern: typeAnnotationPattern, excludingSyntaxKinds: SyntaxKind.commentAndStringKinds, range: $0).first @@ -95,4 +96,15 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul let rhsTypeName = components[1].trimmingCharacters(in: charactersToTrimFromRhs) return lhsTypeName != rhsTypeName } + + private func isIBInspectable(range: NSRange, file: File) -> Bool { + guard let byteRange = file.contents.bridge().NSRangeToByteRange(start: range.location, length: range.length), + let dict = file.structure.structures(forByteOffset: byteRange.location).last, + let kind = dict.kind.flatMap(SwiftDeclarationKind.init(rawValue:)), + SwiftDeclarationKind.variableKinds.contains(kind) else { + return false + } + + return dict.enclosedSwiftAttributes.contains(.ibinspectable) + } }