Adding SwiftLint to a project in Xcode
SwiftLint is a tool for validating the style and conventions in Swift files. It is easy to integrate to a project. Minimum set up consists of installing SwiftLint and adding a build phase to your app target in Xcode. SwiftLint comes with a default list of rules, but if you would like to change the rules then it is required to create a configuration file in yaml. Let’s take a look on how to install, add build step, and use a separate configuration file with a custom set of rules.
SwiftLint is available in homebrew so the easies way is to install it with
brew install swiftlint command. Next step is to add the build phase to a target. I am gonna use one of my example app which is available on GitHub: SwiftPackageAppWorkspace. This project uses a workspace and includes an app project and Swift package.
Click on the ButtonGallery project in the file navigator, then on the iOS target and build phases. Will use the + button for adding a new run script phase. Note that we already use the config argument for letting SwiftLint know where the config file exists (by default SwiftLint looks for
.swiftlint.yml file in the same folder the project file is).
Last step is to add a custom configuration file to the repository checkout. We’ll add it to the checkout’s root folder which is the parent folder of the ButtonGallery.xcodeproj. I have went through the full list of rules available for SwiftLint and picked the ones which match with my coding style. SwiftLint has a list of default rules. The list of evaluated rules can be expanded with
opt_in_rules and rules from default list can be disabled with
disabled_rules list. Also I prefer to have else on a newline so I added
statement_position configuration with
Included defines a list of folder paths relative to the .xcodeproj calling swiftlint.
The next time the target is built it will run SwiftLint with custom configuration and show warnings and/or errors in Xcode.
SwiftLint is easy to set up and helps to keep the code style consistent in projects. In additional to style SwiftLint is capable of suggesting different coding conventions like use enum instead of struct with only static functions. For making it easy to add custom configuration to new project I have set up a command alias in
~/.zshrc which looks like this:
alias xcode_lint_add='cp ~/Dev/swiftlint.yml swiftlint.yml && mate swiftlint.yml' Run
xcode_lint_add in the root of the cloned project.