Setting Up SwiftLint for iOS Code Style Checking
SwiftLint is a static analyzer for Swift code from Realm. It checks compliance with Swift API Design Guidelines and custom team rules. On a project with 5+ developers without SwiftLint, in three months some code will have trailing whitespace, other parts will have force_cast and force_unwrapping scattered everywhere, and yet other parts will have functions 200 lines long.
Installation and Basic Configuration
Via Swift Package Manager (preferred for teams — version is fixed):
// Package.swift or via Xcode → Add Package Dependencies
.package(url: "https://github.com/realm/SwiftLint.git", from: "0.57.0")
Run in Build Phase:
# Build Phase → Run Script
if which swiftlint > /dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
File .swiftlint.yml in project root:
included:
- Sources
- Tests
excluded:
- Sources/Generated
- Pods
- .build
disabled_rules:
- trailing_whitespace # if editor doesn't clean automatically
opt_in_rules:
- array_init
- closure_spacing
- conditional_returns_on_newline
- contains_over_filter_count
- empty_count
- explicit_init
- fatal_error_message
- first_where
- force_unwrapping
- implicitly_unwrapped_optional
- overridden_super_call
- private_outlet
- prohibited_super_call
- sorted_imports
- unneeded_parentheses_in_closure_argument
line_length:
warning: 120
error: 200
function_body_length:
warning: 50
error: 100
file_length:
warning: 400
error: 600
type_body_length:
warning: 200
error: 400
cyclomatic_complexity:
warning: 10
error: 20
custom_rules:
no_print:
name: "No print statements"
regex: "\\bprint\\("
message: "Use Logger instead of print()"
severity: warning
Autocorrect in CI
SwiftLint can automatically fix some violations:
swiftlint --fix --format
In CI, this is used as a separate step: fixes and commits changes back to the branch. But usually it's more reliable — run --fix locally via pre-commit hook.
Pre-commit Hook
#!/bin/bash
# .git/hooks/pre-commit
git diff --cached --name-only --diff-filter=ACM | grep "\.swift$" | while read FILE; do
swiftlint lint --path "$FILE" --quiet
if [ $? -ne 0 ]; then
echo "SwiftLint failed for $FILE"
exit 1
fi
done
Or via lefthook / pre-commit framework — easier for team management.
CI Integration
- name: Run SwiftLint
run: |
swiftlint lint \
--reporter github-actions-logging \
--strict
--strict turns warnings into errors. --reporter github-actions-logging outputs violations in GitHub PR Annotations format — they display directly on code lines in PR Review.
Timeline: 1 day. Cost is calculated individually.







