realm / SwiftLint

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

unused_declaration does not catch View only used in PreviewPeovider #4720

Open iressler opened 1 year ago

iressler commented 1 year ago

New Issue Checklist

Describe the bug

When a View is only used by it's matching PreviewProvider unused_declarations does not report it as unused. E.g. if this is in a file and the View is not referenced anywhere else SwiftLint will not report any issues:

struct UnusedView: View {
  var body: some View {
    Text("Hello, World!")
  }
}

struct UnusedView_Previews: PreviewProvider {
  static var previews: some View {
    UnusedView()
  }
}

This may be expected behavior, the View is being used, however I was surprised by it and don't consider that a "real" use. If this isn't reported as unused then no SwiftUI View with a Preview will ever be "unused", even though they aren't actually being used anywhere.

Complete output when running SwiftLint, including the stack trace and command used
$ swiftlint analyze --compiler-log-path <path>
Analyzing Swift files in current working directory
Collecting 'UnusedDeclarationsPreviewsApp.swift' (1/3)
Collecting 'ContentView.swift' (2/3)
Collecting 'UnusedView.swift' (3/3)
Analyzing 'UnusedDeclarationsPreviewsApp.swift' (1/3)
Analyzing 'ContentView.swift' (2/3)
Analyzing 'UnusedView.swift' (3/3)
Done analyzing! Found 0 violations, 0 serious in 3 files.

Environment

analyzer_rules:
  - unused_declaration
SimplyDanny commented 1 day ago

Seems to be a good idea to add an option to the rule that makes it treat types only used in previews as unused.