swiftswiftlint

SwiftLint analyzer removes imports if using of static calls (not desired behavior)


In my project I use a SwiftLint analyzer, in order to remove all unused imports I use these lines

xcodebuild -workspace lintanalize.xcworkspace -scheme MY_SCHEME -configuration Debug > xcodebuild.log
swiftlint analyze --fix --compiler-log-path xcodebuild.log

It really works and the analyzer knows how to remove unused imports, however, the problem is that it wrongly removes those imports where only static calls, for example:

import PhotosUI

class PermissionPhotos {
    func request(_ callback: @escaping (PermissionStatus) -> Void) {
        PHPhotoLibrary.requestAuthorization(for: .readWrite) { ... }
    }
}

In the example I use PHPhotoLibrary static method call requestAuthorization, so the analyzer will remove import PhotosUI as it thinks that the static call is not using this import

Is there a way to fix it?

UPD

I also noticed that the same behavior related to the params, for example

import PhotosUI

class PermissionPhotos {
    func request(myvalue: PHPhotoLibrary) { ... }
}

In this case, PHPhotoLibrary uses as a param, so the analyzer will miss this and will remove import PhotosUI, looks like the analyzer see only the actual definition of objects like

let myobj = PHPhotoLibrary()

Solution

  • Your swiftlint.yml file can be used to make some rule bending modifications / customizations. Refer this page for rules related to unused imports - https://realm.github.io/SwiftLint/unused_import.html and check the section Default configuration

    My best bet is you should turn on require_explicit_imports.