SwiftLint Knowledge

Kip Landergren

(Updated: )

My SwiftLint knowledge base explaining its purpose, use, and best practices.

Contents

Overview

SwiftLint is a configurable linter that provides hooks to check, and sometimes correct, issues with swift code. These issues are codified into “rules” that define a specific condition to take action on. Largely these rules will fall under the category of “style”—things that do not affect the compiled result but do affect the code reader—but some also may prevent true bugs and act as proxies for code base health.

Rules are configurable through a default configuration file $PROJECT_ROOT/.swiftlint.yml and may be merged with other configuration files located in sub-directories. Control can also exist with the source code with specific keywords for enabling and disabling. Additionally, some rules are explicitly opt-in.

Refer to SwiftLint Reference for more specific information on rules, configuration, and usage.

SwiftLint may be integrated for use directly in a user’s editor, via an offline continuous integration job, or straight from the command line.

Using a static analysis tool like the SwiftLint linter improves your codebase’s consistency, teaches through enforcement, and catches potential issues automatically.

Core Idea

Use SwiftLint to check your swift codebase against a corpus of community-sourced rules representing stylistic, bug-preventing, and best practice code patterns. Control its execution and operation through command line arguments, configuration directives, and customized rule behaviors. Reporting is available in-editor by hooking into the build process or externally through command line invocation.

Best Practices

Avoid Enabling All Rules

Adherence to the set of all rules defined do not represent some “best” state of a swift codebase; discover what subset of rules best fit the use case for your situation. Additionally, some rules are directly orthogonal to each other!

Use Multiple Configuration Files

For fast prototyping and iteration, consider employing one configuration file with a minimal set of rules within whitelist_rules and a second configuration file with more restrictive set of rules enabled.

Configure SwiftLint per Target

Create additional targets as needed for additional SwiftLint configuration, either for rule enforcement or for functionality.

Accept that SwiftLint is Fallible

An error or warning is not a definitive declaration: sometimes there are false positives or bugs that crop up. Use your judgment.

Key Concepts

Linting

Linting is a form of static analysis where the source code—typically the abstract syntax tree—is inspected for patterns defined by a set of rules.

A linter’s job is not to be the compiler. A linter’s job is to weigh multiple ways of doing something and prefer one.

Use a linter to improve consistency, avoid bad practices, improve readability, deflect style debates, and enforce specific patterns.