SwiftLint
SwiftLint copied to clipboard
Rule Request: [explicit_init] - avoid using `let cl: Class = .init()`
New Issue Checklist
- [x] Updated SwiftLint to the latest version
- [x] I searched for existing GitHub issues
New rule request
Please describe the rule idea, format
this issue's title as Rule Request: [Rule Name]
and describe:
Improve rule explicit_init
to force user to use let cl = Class()
instead of let cl: Class = .init()
- Why should this rule be added? Share links to existing discussion about what the community thinks about this.
Code is more readable when you initialize with class name instead of .init() only
- Provide several examples of what would and wouldn't trigger violations.
NO:
let view: UIView = .init(frame: .init(origin: .init(x: 0, y: 0), size: .init(width: 50, height: 50)))
YES:
let view = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 50, height: 50)))
- Should the rule be configurable, if so what parameters should be configurable?
I guess no.
- 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 guess it should be enabled by default.
I've created a simple custom rule for that:
init_with_class_name:
name: "Init With Class Name"
regex: "((=|,|\\[|:|return)\\s*\\.init\\()"
message: "There should be init function with class or structure name. EG: let cl = Class() instead of let cl: Class = .init()"
severity: warning
@jendaz can you please fill the template? it really helps whoever decides to work on this!
I've created a simple custom rule for that:
init_with_class_name: name: "Init With Class Name" regex: "((=|,|\\[|:|return)\\s*\\.init\\()" message: "There should be init function with class or structure name. EG: let cl = Class() instead of let cl: Class = .init()" severity: warning
This pattern doesn't handle this following case
optionalValue ?? .init(...)
This should be a more accurate & efficient rule:
init_with_class_name:
name: "Init With Class Name"
message: "Prefer let object = Class() instead of let object: Class = .init()"
included: ".*.swift"
regex: '(?<!self|super)\.init\('
match_kinds:
- identifier
- keyword
severity: warning
also, do we have an update on this issue?
I'd love to see this officially supported 👍🏻
I have actually implemented this rule. I don't think I kept my branches (I built it as a demo), but it was very easy, at least to catch all .init
cases.
I'm curious as to why you think
let view: UIView = .init(frame: .init(origin: .init(x: 0, y: 0), size: .init(width: 50, height: 50)))
should not trigger.
and how about?
let x: [SomeObject] = [
.init(someArg: someArg)
.init(someArg: someOtherArg)
]
I assumed they meant the
NO
case wouldn't trigger and
YES
would
and I would personally say that array example should trigger. Maybe a level of strictness could be configurable?
Work in progress ^^^^
Awesome! Is there a timeline for a new release?