SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

`optional_data_string_conversion` does not trigger when `.init(decoding:as:)` is called instead of `String(decoding:as:)`

Open zenfty opened this issue 1 year ago • 3 comments

New Issue Checklist

Bug Description

As the title suggests, optional_data_string_conversion does not trigger when calling String.init() instead of directly calling String().

Example:

// This triggers a violation:
let text = String(decoding: data, as: UTF8.self)

// This does not trigger a violation:
let text: String = .init(decoding: data, as: UTF8.self)

(swiftlint is in its default configuration, ran by xcode)

Environment

  • SwiftLint version — 0.62.2
  • Xcode version — 26.1 (17B55)
  • Installation method used (Homebrew, CocoaPods, building from source, etc)
  • Configuration file:
# n/a?

Are you using nested configurations? If so, paste their relative paths and respective contents. N/A

zenfty avatar Nov 27 '25 10:11 zenfty

This could be supported. However, I'd hide it behind an option since we cannot be 100% sure that .init(decoding: data, as: UTF8.self) refers to String.init(decoding: data, as: UTF8.self).

SimplyDanny avatar Nov 27 '25 19:11 SimplyDanny

Implemented this in #6508.

I added include_shorthand_init (default false) so shorthand .init(decoding:as:) can be linted when desired, while avoiding ambiguous cases by default.

theamodhshetty avatar Feb 24 '26 05:02 theamodhshetty

Opened #6567. This extends optional_data_string_conversion to catch the equivalent String.init(decoding:as:) and contextual .init(decoding:as:) spellings, so they get the same treatment as the existing String(decoding:as:) case. I also added explicit examples for both forms and ran the generated rule test plus a strict lint pass on the touched files.

theamodhshetty avatar Mar 30 '26 04:03 theamodhshetty