Reputation: 425
SwiftLint - How to allow one line guard conditionals like this:
guard let x = true else { return false }
and keep conditional_returns_on_newline
functionality for other cases?
Edit:
As far as I know SwiftLint defines rules of violations so I have to write regex that scans lines through in search for:
if[...]{[...]}
Please be also aware of the cases like these:
if array1.sorted(by: { $0 > $1 }).first! > 0, array2.isEmpty { x = 1 }
Upvotes: 1
Views: 2279
Reputation: 2953
SwifLint rule conditional_returns_on_newline
is Disabled by default. So,
conditional_returns_on_newline
rule.if_only
to true
No need to write any custom rules
.swiftlint.yml configuration:
opt_in_rules: # some rules are only opt-in
- conditional_returns_on_newline
conditional_returns_on_newline:
if_only: true
Here is the rule link:
https://realm.github.io/SwiftLint/conditional_returns_on_newline.html
Upvotes: 2
Reputation: 425
I think I was able to find a satisfactory solution:
conditional_returns_on_newline
.custom_rules:
custom_conditional_returns_on_newline:
name: "Conditional returns on new line"
regex: '^[\h]*(if|else|while)[^\n]*\}$'
message: "If/else and while constructions should not be defined in one line"
severity: warning
custom_rules
to whitelist_rules
.Upvotes: 1
Reputation: 6067
There are two ways to achieve it.
You can disable the conditional_returns_on_newline
rule. You can disable it at the code blocks level, source file level, or at the project level by updating the rules file which is kept inside your project code folder. Doing so will disable the rule for each such statements (depends on the disabling scope) like if true { return }
or if true { return "YES" } else { return "NO" }
etc. Here is the explanation and I think you don't want to do it.
The second is to write your own regex rules. You can define your custom regex-based rules in your configuration here is the detail explaination
High-level implementation for point 2, follow the below steps.
.swiftlint.yml
and disable the given rule conditional_returns_on_newline
at the project level.ks_conditional_returns_on_newline
) to your .swiftlint.yml
file,
You can decide the rule name
, message
, severity
, and
included
etc parameters as per your need.custom_rules:
ks_conditional_returns_on_newline:
included: ".*\\.swift"
name: "Custom Conditional Returns On New Line"
regex: "(if)[^\n]*return"
message: "Hey look at the the conditional returns on newline for if else"
severity: error
I have validated the rule regex with Xcode and it worked fine. Though, I have not verified adding it to .swiftlint.yml
. But I am hopeful it will work.
Upvotes: 1