SwiftLint

SwiftLint is a tool to enforce Swift style and conventions. It is developed by Realm.

Installation:

In this page, we will install SwiftLint via Homebrew.

Open terminal and run

$ brew install swiftlint

Once installed, navigate to your project folder in terminal and create .swiftlint.yml file:

$ touch .swiftlint.yml

swiftlint.yml file is where we define how the linter configuration will be. In the configuration file, you can add, disable or update the linting rules.

You can see a sample of this file’s structure at here.

Rule inclusion in .swiftlint file:

  • disabled_rules: Disable rules from the default enabled set.
  • opt_in_rules: Enable rules not from the default set.
  • only_rules: Only the rules specified in this list will be enabled. Cannot be specified alongside disabled_rules or opt_in_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 are no equivalents for disabled_rules only_rules.

Open the .swiftlint.yml file to edit:

$ open .swiftlint.yml

After you have configured the .swiftlint.yml file, save it and close.

Then navigate into your project – XCode Target > Build Phases > + icon > Create New Run Script Phase

Add below script:

if which swiftlint >/dev/null; then
  swiftlint
else
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Place your build script in top of Build Phases, Then build your project.

In my example project below, SwiftLint’s script is the second one.

There is a built-in feature in SwiftLint by which can correct some type of violations automatically.
Run below command in the root directory of your iOS project to autocorrect:

$ swiftlint autocorrect

When you run above command files on disk are overwritten with a corrected version. So to be aware that you have backups of these files before running, swiftlint autocorrect in case some datas can be lost.

Now that you have configured your linter in XCode, you may want to check some common Swift Style guides as well.

Run swift lint in custom iOS file

  • add your file location in -included tag:
included:
  - Source
  - Tests
  - ../

Here is my custom .swiftlint file.

Here you can find the source code and learn more about SwiftLint.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s