How to enforce the Swift coding styles & conventions

Kamar Shad
5 min readJun 13, 2020

--

Problem statement

Nowadays writing code is not a big deal but sometimes writing well-organized & performant code is a tedious task even if you have proper coding guidelines in place. But still, you or maybe your teammates jump or forget to adhere to the in-place coding guidelines.

What if we have an automated system, a library, that imposes all the defined rules in your working project that validates each of the code you write in your working project. If you or your team member go off the guidelines. They will immediately be intimated with appropriate flags (with warnings or errors). No, I am not talking some imaginary stuff, it’s doable we have many open-source libraries once we can include them to our project. Our job becomes easy, that library will keep validating the coding rules/guidelines.

Now, You got me, Yes, I am talking about Swiftlint (https://github.com/realm/SwiftLint). It’s a great library that enforces the Swift style and conventions. It provides over 75 rules and the best part of this library is, you can modify define your own custom rule. Also, you can modify the existing rules as per your requirement. Is not it exciting? In this article, I will talk about how to use it, modify, and add our own custom rules. Without wasting a moment, let’s jump to the implementation.

How to Install and use it

We can use this library in various ways. Some of the ways are listed below

Using Homebrew, to install it using the hombrew, run the below command from your mac terminal
brew install swiftlint

Using CocoaPods, add the following line to your Podfile and run the pod install command from mac terminal
pod `SwiftLint`

There are many other ways we can install it in our project, go through the documentation (https://github.com/realm/SwiftLint#installation) and install as per your wish. But the recommended way is to install it using Pod since it supports installing a pinned version rather than simply the latest and which is the case with Homebrew.

Integrate with your Xcode project

In order to integrate SwiftLint with Xcode project target to get warnings and errors displayed in the Xcode, you just need to add a new Run Script Phase with the following script

If you are not sure, how to add it follow the instructions below.

Build

Once you are done with Run Script and builds your Xcode project, you might notice a couple of warnings as attached screenshot.

Rules and Configuration

We can configure SwiftLint rules as per our need by adding a .swiftlint.yml file from the directory we run SwiftLint from. Let’s first talk about the configuration parameters.

  • opt_in_rules are disabled by default (i.e., you have to explicitly enable them in your configuration file). These are the rules that can have many false positives, a rule that is too slow or a rule that is not in general consensus or is only useful in some cases (e.g. force_unwrapping).
  • disabled_rules: Disable rules from the default enabled set.
  • whitelist_rules: Only the rules specified in this list will be enabled. Can not be specified alongside disabled_rules or opt_in_rules.Also when we create a new custom rule, we have to place it under the whitelist_rules.
  • analyzer_rules: This is an entirely separate list of rules that are only run by the analyze command. All analyzer rules are opt-in, so this is the only configurable rule list (there is no disabled/whitelist equivalent).

To know which rule is placed under the opt_in_rules, correctable (auto correctable by running swiftlint autocorrect command), enabled in your configuration, kind, and configuration (whether configured as a warning or an error). Run the swiftlint rules command. Once you run the command it will print the details similar to the given screenshot.

I am attaching the .swiftlint.yml which gives you a better understanding of rules configuration.

How to modify or disable a rule?

Sometimes, default configured rules do not suit our requirements. We may require to update rule definition or we may require to exclude some of the rules for some classes or specific folders.

Disable rule at the project level
Disabling a rule at the project level is not a good idea though sometimes we may need to disable it. We just need to place that particular rule in the disabled_rules category. Make sure you have the .swiftlint.yml placed inside your project folder.

Disable rule within a source file
We can disable the rules within source file with the given format
// swiftlint:disable <rule1> [<rule2> <rule3>...]
This way rules will be disabled until the end of the file or until the linter sees a matching enable comment like as below
// swiftlint:enable <rule1> [<rule2> <rule3>...]

Or if we want to we can use all keyword and it will disable all rules until the linter sees a matching enable comment
// swiftlint:disable all // swiftlint:enable all

As you can see in the attached screenshot below. I have disabled the identifier name rule for constant i. It is not getting any violation triggered. But for constant j identifier name violation is triggered. Because as soon the linter sees the enable rule command. It enabled the rule again for the subsequent lines.

Disable the rules

How to add a custom rule?

SwiftLint provides an easy way to add a custom rule. In order to add a custom rule, we need to define custom regex-based rules in our swiftlint.yml configuration.

For example, we have a use case where we don’t want to apply the conditinal_return_on_newline for guard statement but want to keep it applicable for the rest of the conditional statements. we can create a custom which skips the validation for guard statement but validate the rest of the conditional statements.

  1. Disable the conditional_returns_on_newline the rule for the whole project. Put this rule under disabled_rules in the configuration file
  2. Define a custom regex-based rules in your configuration
  3. Add a newly created rule in whitelist_rules the section of .swiftlint.yml

The possible .swiftlint.yml configuration file will look like an attached screenshot.

This is just an example, you may have other configurations available in swiftlint.yml

Note- When we need to add a new rule which is not provided in the swiftlint rules. Then form a valid regex, define it under the custom_rules ( in .swiftlint.yml) with all required parameters, and add it to the whitelist_rules section.

Recap

SwiftLint helps us to enforce swift coding styles and conventions. Also, allow us to modify existing rules, disable or add a new custom rule as per our requirements. This was a small insight into SwiftLint, I would suggest you dive into it to use in better way.

I hope you like this article. Suggestion and feedback are most welcome
Enjoy ✌️😊

--

--