realm / SwiftLint

A tool to enforce Swift style and conventions.
https://realm.github.io/SwiftLint
MIT License
18.57k stars 2.21k forks source link

Rule Request: Warn on use of some NS types in Swift code #2758

Open 72A12F4E opened 5 years ago

72A12F4E commented 5 years ago

New Issue Checklist

New rule request

Please describe the rule idea, format this issue's title as Rule Request: [Rule Name] and describe:

  1. Why should this rule be added? Share links to existing discussion about what the community thinks about this.

This would prevent developers from using legacy NS types where swift versions of those types already exist. Apple outlines guidance on which types get bridged here:

https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/working_with_foundation_types

  1. Provide several examples of what would and wouldn't trigger violations.

Bad

All of the below types have a Swift analogue and should not be used in Swift code

let foo1: NSDictionary = bar1
let foo2 = NSArray()
let foo3: NSString = bar3
let foo4 = NSSet()

Ok

These types do not have a Swift analogue, so they should be allowed.

let vc = NSViewController()
let orderedSet = NSOrderedSet()
  1. Should the rule be configurable, if so what parameters should be configurable?

Unsure

  1. Should the rule be opt-in or enabled by default? Why? See README.md for guidelines on when to mark a rule as opt-in.

I think this rule should be opt-in. There is a lot of potential for flagging types that should be completely valid in normal Swift code, and in codebases where very particular Swift-ObjC is required.

72A12F4E commented 5 years ago

Here is a regex based rule that I implemented to identify these issues. I hope it helps!

custom_rules:
  legacy_objc_type:
    included: ".*.swift"
    name: "Legacy Obj-C Type"
    regex: "NSAffineTransform|NSArray|NSCalendar|NSCharacterSet|NSData|NSDateComponents|NSDateInterval|NSDate|NSDecimalNumber|NSDictionary|NSIndexPath|NSIndexSet|NSLocale|NSMeasurement|NSNotification|NSNumber|NSPersonNameComponents|NSSet|NSString|NSTimeZone|NSURL|NSURLComponents|NSURLQueryItem|NSURLRequest|NSUUID"
    message: "Avoid using Obj-C types when Swift types will suffice."
    severity: warning
    match_kinds:
      - typeidentifier