1 minute read

Using SwiftLint to keep your code clean

Swift can compile cleanly and still contain code that is difficult to maintain: a 180-line view controller, inconsistent naming, a forced cast, or a function that hides three jobs. SwiftLint performs static analysis by checking source files against configurable style and complexity rules, turning those concerns into named warnings before they become review comments. It does not judge architecture or replace tests; it makes questionable patterns visible while changes are still fresh.

For a junior iOS developer, consistency matters because small habits scale across a project. Repeated decisions about spacing, identifier names and function size create noise in pull requests. Automated linting lets reviews focus on behaviour, accessibility and product decisions instead of formatting basics, while teaching the conventions expected by teams shipping Swift apps.

The workflow travels beyond a single Mac. Sydney and Melbourne have busy iOS product teams, while Australian banks, supermarkets, health services and education providers maintain apps for a local market with demanding privacy and reliability expectations. The same standards can run on a developer’s Mac, in a remote team’s GitHub Actions pipeline and beside Xcode builds. This guide uses Australian English, including “organisation” and “behaviour,” while preserving API names such as UIColor.

Tool Main responsibility Typical finding Best used for
Swift compiler Type and semantic correctness Invalid types or language usage Every build
SwiftFormat Deterministic formatting Spacing and layout differences Before linting or committing
SwiftLint Configurable code-quality rules Long functions, unsafe casts and unclear names Editing, review and CI

Why linting belongs in an iOS workflow

A compiler answers a narrower question: does the program type-check and satisfy the language rules? SwiftLint asks whether the source follows the conventions selected by the project. It can flag long functions, broad types, unsafe force unwraps, redundant conditions and naming that obscures intent. These are not compile errors, yet each can increase the cost of changing an app.

Linting is most valuable during editing, not as a final green tick. If a view controller grows past the team’s threshold, the warning arrives while the change is small. If a cast is forced without a clear fallback, it appears beside the relevant line. Xcode still provides navigation and compilation, but the lint result gives maintainability a shared vocabulary.

SwiftLint should complement a formatter rather than compete with it. SwiftFormat can rewrite spacing and deterministic layout; SwiftLint reports patterns that usually require judgement. Run formatting first, then linting, so length and whitespace warnings describe the final source. This division keeps automation focused on repeatable structure and leaves design decisions with reviewers.

Installing SwiftLint on macOS

Homebrew is the simplest repeatable installation for most Mac-based iOS developers:

brew install swiftlint
swiftlint version

A package manager keeps the command available to local builds and continuous integration without adding a runtime library to the app bundle. On a work machine managed by an organisation, ask the team which version is approved, then record it in the project setup documentation.

Teams can use Mint or a bootstrap script to pin the tool version. Xcode project dependencies are useful for frameworks an app links, but a command-line linter still needs a stable path in every environment. An informal manual installation is risky because a clean CI runner will not inherit the developer’s Downloads folder.

After installation, run swiftlint from the repository root so it discovers .swiftlint.yml and the intended source directories. A quick swiftlint lint confirms the tool can see the project; a noisy first report is useful information rather than a reason to remove the configuration. Teams across Australian Eastern and Central time zones can agree on the same command because its result does not depend on local clock settings.

Choosing rules that suit the project

A useful configuration is small enough to understand and specific enough to expose meaningful drift. Start by excluding dependencies, generated interfaces and build products; otherwise third-party code can dominate the report. A practical root file might look like this:

excluded:
  - Pods
  - Carthage
  - Generated

opt_in_rules:
  - empty_count
  - empty_string
  - redundant_nil_coalescing

The project should decide whether comments are ignored by length checks, how strict identifier names must be and when a function is too large. Thresholds belong in the shared file because one developer’s screen width should not determine the result. If a rule repeatedly flags a legitimate Swift pattern, refine it or document a narrow exception rather than quietly raising every limit.

Two short review lists help separate dependable defaults from noisy candidates:

Strong candidates for a shared configuration

  • Set line_length with a project limit that suits the codebase.
  • Use function_body_length to expose functions that mix several jobs.
  • Apply identifier_name to catch unclear short names.
  • Enable trailing_whitespace to prevent invisible source noise.

Rules to trial on one module first

  • Trial type_body_length on models with many responsibilities.
  • Trial file_length to find source files that keep growing.
  • Use cyclomatic_complexity to surface deeply branched logic.
  • Review todo markers before a release rather than hiding them.

Resolving warnings without changing behaviour

Triage by consequence rather than warning count. A force unwrap around user input can remove a crash path, while a naming violation usually does not change runtime behaviour. Read the surrounding code, reproduce the relevant path and write a test when behaviour is uncertain. Renaming a property for clarity is safe; replacing as! with as? is not equivalent because it introduces a missing-value case that the caller must handle.

Many warnings are best fixed by redesigning a small boundary. Split a function that fetches data, maps a model and updates the interface into named helpers. Replace a magic number with a typed constant. Use guard let when a missing value should stop the current operation. The goal is not to satisfy the linter mechanically but to leave code whose purpose is easier to see.

For a deliberate, documented exception, scope the suppression to the smallest useful region:

// swiftlint:disable:next force_cast
let model = data as! Model

A line-level command is easier to review than disabling a rule across an entire file. SwiftLint does not automatically rewrite every semantic issue it detects, so each refactor still needs compiler checks and tests. Re-run the linter after a fix to ensure the warning disappeared for the right reason.

Running checks locally and in CI

Run the same command locally that CI will run. From the repository root, swiftlint lint --strict treats warnings as failures and prevents differences between an editor’s severity settings and the server’s. In Xcode, a shared Run Script build phase can invoke the installed binary for fast feedback, but the phase must not swallow its exit status; otherwise the build continues after a failed check.

Continuous integration should archive the report even when the job fails. A JSON reporter can be saved for later inspection:

swiftlint lint --strict --reporter json > swiftlint-report.json

Keep the configuration and tool version in source control so a result can be reproduced. For broader Xcode habits, Askar’s iOS development notes offer a useful companion workflow for connecting project structure, previews and repeatable checks.

Introduce strict mode gradually for an existing codebase. Fix a small family of warnings in a dedicated pull request, review the diff for behavioural changes and expand the rule set only after the team agrees on the expected result. A steadily falling warning count is more useful than an artificial zero created by exclusions. On pull requests, show only new warnings where the tooling allows it, while retaining full logs for maintainers.

Building a repeatable cleanup routine

Make linting a habit rather than a rescue operation. Before committing, run the project command and resolve warnings in the files you touched. During a weekly cleanup, choose one recurring rule, inspect every occurrence and decide whether the pattern needs a shared helper, a clearer type or a revised rule. This turns the report into a map of design friction instead of a list of minor offences.

Track the number of warnings, the files affected and the age of older findings. A rise after a large feature may point to a missing abstraction rather than poor intentions. Pair the measurements with code review, unit tests and UI checks: linting can reveal suspicious structure, but it cannot prove that a screen behaves correctly. Keep local suppressions only when they explain a genuine boundary, and remove them once that boundary changes.

Announce new rules in the pull request that enables them, explain the problem they solve and keep severities consistent across environments. For distributed teams in Brisbane, Perth and Adelaide as well as the eastern capitals, a deterministic report that every timezone sees identically matters more than overlapping office hours. The first action is to install SwiftLint in one small Xcode project, run swiftlint lint once and save the output as swiftlint-report.txt.

Updated: