SwiftLint in Depth

Learn how to use and configure SwiftLint in detail, as well as how to create your own rules in SwiftLint for your project. By Ehab Amer.

5 (6) · 4 Reviews

Download materials
Save for later
Share

Building good apps isn’t only about writing bug-free code. It’s also about writing code that requires less effort to understand and build on. Imagine you’re reading a magnificent novel, but the font is hard to read and the layout is messy. This novel would take more effort to read. And no matter how good the novel is, you’ll still have mixed feelings about it and the author’s skills.

Writing code is no different. Messy and inconsistent code takes more effort to read. Fortunately there are tools out there to help you write code that is consistent in style. Enter SwiftLint!

In this tutorial, you’ll learn:

  • What SwiftLint is.
  • How to install SwiftLint and integrate it into your projects.
  • Some of the coding rules SwiftLint checks.
  • To control which rules you want to enable and disable in your project.
  • How to create custom rules.
  • How to share a rules file across your different projects or the team.

Getting Started

Download the starter project by clicking the Download materials link at the top or bottom of the tutorial.

Throughout this tutorial, you’ll work on MarvelProductions. It lists movies and TV shows Marvel has already published or announced.

Marvel Productions app running

Open the starter project and take a look around.

Before moving forward with the tutorial, change the workspace setting for the DerivedData folder of this workspace to be relative to the project and not in the default location. This will download the SPM package inside the your project folder which is needed for demo purposes during the tutorial. You can find this setting from the menu File ▸ Workspace Settings.

Changing DerivedData location setting

What Is SwiftLint?

Before diving into code, you should know a little about SwiftLint. While building your app, you’ll focus more on the code itself instead of on how to keep the code organized. SwiftLint is all about your code organization rather than the logic you’re implementing. For example SwiftLint can help you to enforce the maximum number of lines a file or a method should be. This prevents writing super long methods or creating a file with too many classes or methods inside it.

As you work with different teams, each will likely have its own set of guidelines they follow. SwiftLint helps developers to specify a set of conventions and guidelines. So everyone contributing to the project follows it.

How SwiftLint Works

SwiftLint goes through files in your project directory and looks for certain patterns. If it finds any, it reports them through a message on the command line.

The app runs from the command line and doesn’t have any interface of its own. So to use it, you need to do two things:

  1. Install SwiftLint on your computer.
  2. Add a Run Script phase in your build steps of your Xcode project which runs SwiftLint.

Installing SwiftLint

You have many options to install SwiftLint, including CocoaPods or Homebrew. In any case, it’ll work the same. The former will install it in the project. So everyone working on the project will have it while installing the dependencies. The latter will install it on your machine so you use it in all your projects.

There’s no right or wrong, better or worse. It’s all a matter of preference. For this tutorial, you’ll use the latter option, Homebrew.

Installing Homebrew

Note: If you already have Homebrew installed on your machine, skip this part.

Homebrew is a package manager for utilities on macOS. It makes life a lot easier by installing utilities you use on your computer and managing any dependencies those utilities may have.

Installing Homebrew is simple as running this command from Terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Installing SwiftLint

To install SwiftLint with Homebrew, run this command in Terminal after installing Homebrew.

brew install swiftlint

This will install the latest version of SwiftLint.

Note: If you want to install a specific version of SwiftLint, you need to use something other than Homebrew. Either download the version you want from SwiftLint releases on GitHub or use Mint.

Using Terminal

Now that you have SwiftLint installed, why not try it?

In Terminal, navigate to your starter project. A simple way to do that is to type cd (with a space after cd). Then, drag and drop the folder from Finder to the Terminal window to paste the folder path in Terminal. Then press Return to execute the command.

Drawing the starter project file on the Terminal window instead of typing the path

Next, type the following into your terminal:

swiftlint

You’ll see many messages in Terminal, some of which look like this:

..../MarvelProductionItem.swift:66:1: warning: Line Length Violation: Line should be 120 characters or less; currently it has 173 characters (line_length)

These lines are warnings and errors that SwiftLint has found in your project. The last message will end something like this:

Done linting! Found 144 violations, 17 serious in 165 files.

This tells you how many total warnings and errors there are, how many are serious, and how many total files have been scanned.

This is how SwiftLint works. There’s more, of course, but as far as how it’s executed and runs, that’s it!

Next is to report these messages in Xcode and show you the file and line containing the violation.

Xcode Integration

Xcode allows messages from a command line operation to appear on top of source code, like syntax errors or warnings.

Open MarvelProductions.xcworkspace in the starter project. Select the MarvelProductions project file at the top of the Project navigator. Then click on the MarvelProductions target and finally select the Build Phases tab. Click the small + button at the top-left to add a new phase and select New Run Script Phase from the menu.

Adding a new Run Script Phase from the menu

When you build the project, it’ll run the commands entered in this step as if you were entering them on the command line. Xcode will also receive messages from the executed command and include them in the build log.

Note: You can change the order of the build steps by dragging the new run script phase and moving it up to execute earlier. This can save you time to see results from this script before other operations.

Open up the new Run Script build phase and replace the text in the large text box underneath Shell with the following:

echo "${PROJECT_DIR}/MarvelProductions/DataProvider/ProductionsDataProvider.swift:39:7: error: I don't like the name of this class!"
exit 1

The new commands entered in the new Run Script phase

Make sure to uncheck all the checkboxes.

The aim of this script is to show you how you can report an error in one of the files in the project. Here is what’s going on in the script above:

  • echo: A Terminal command that prints out the string that follows it. It’s like print(:) in Swift. In this script, Xcode prints all the text that follows it.
  • ${PROJECT_DIR}: An environment variable defined by Xcode that translates to the folder path of the project file. This way, it doesn’t matter if you have the project on your desktop or anywhere else – the script remains the same.
  • /MarvelProductions/DataProvider/ProductionsDataProvider.swift: The file you are reporting an error in is ProductionsDataProvider.swift. This string is the path of the file relative to the project file.
  • :39:7:: The line and column number in the code file Xcode will mark with the message.
  • error:: The type of message to show. It can be an error, warning or note.
  • I don’t like the name of this class!: The text to appear in the message.

Build the project. The build operation will fail and show you an error in ProductionsDataProvider.swift with the message I don't like the name of this class! and a small cursor under the first letter of the class name.

An error message appearing on ProductionsDataProvider.swift

The last line exit 1 means there was an error from the operation and Xcode should fail the build. Anything other than 0 (zero) means an error, so 1 doesn’t mean anything special.

Feel free to change the file, line, type of message and the message text and rebuild the project. But note the colons because Xcode expects the message in this special format to show the message on the source code. Otherwise, a standard message will appear in the build log.

Once you’ve completed it, replace the script with the following to integrate SwiftLint into your project:

export PATH="$PATH:/opt/homebrew/bin"
if which swiftlint > /dev/null; then
  swiftlint
else
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

This is the recommended script to execute SwiftLint through Xcode. The first line is crucial when using a Mac with an Apple Silicon processor. The script also checks whether you have installed SwiftLint. Otherwise, it prints a message to remind your team members who need to install it.

Build the project. You’ll see all errors and warnings reported in Xcode like it usually reports syntax errors.

Build failed with 17 errors and 124 warnings

Time to fix up those errors! But first, let’s take a look at how SwiftLint defines the rules that it follows.