Loading

Swift Lint

I'm not a great fan of lint programs. Most of the ones I have had experience of have been a right royal PITA. They tend to over-analyse your code, to pick out every trivial style issue whether it has a significant impact on the code or not. Technically, that is what they are for. Just most of them seem to go so over the top that you end up missing the issues in a sea of trivia.

Swift has it's own lint program. And I thought I should give it a go. Glad I did.

Install

There is a GitHub repo with the details, so that's a good place to start.

Swiftlint on GitHub

Installing is a one-off task and consists of running:

brew install swiftlint

That gets it on to your machine. Now, you can run it as a command line and that's what I've seen shown the most. It's fine to do that, but it gives you a get out of jail free card by letting you ignore it or ignore the issues it raises. A better approach is to get it to run every time you build your project. Its a great incentive to fix the issues rather than pretend they're not there.

Integrate into Xcode

Integrating it into your project is as simple as adding a new script action:

Swiftlint auto-scan action

  1. Select the target.
  2. Select the Build Phases tab.
  3. Click the + and add a run script phase.
  4. Add the script.

The code of the script is

if which swiftlint >/dev/null; then
    swiftlint
else
    echo "Warning: SwiftLint is not installed"
fi

Now, every time you build, it will run Swiftlint against that project. If you have multiple projects within the workspace, then you'll need to add the script to each of the ones you want checked. This is pretty useful when you have a load of dependencies introduced with the likes of Cocoapods, where third party code is added to your workspace.

Configuring

Ok, so not every test is a problem and not every setting will meet your requirements. Swiftlint is configurable to allow you to disable some tests, introduce some disabled ones or adjust the parameters of enabled tests. Config is stored in a file called .swiftlint.yml in the same folder as your project. Watch out! That file name starts with a full-stop.

I prefer not to change too many of the rules, so my default yml only has two overrides:

line_length: 160
vertical_parameter_alignment: disabled

The default for line length is stupidly short, so I give myself some leeway. The rule for vertical parameter alignment is just an irritation to me. I like to live up continuation lines my own way, so I have to turn this off.

Automated cleanup

There are some rules that feel trivial and that you propagate without thinking of them too much. Luckily, some of them are fixable with Swiftlint itself.

To do that, open the terminal at the folder where the project is in stalled and type

swiftlint autocorrect

It'll go through and fix a load of simple issues for you automatically. A very useful thing to do when you first set-up swiftlint in the project.