Introducing Swift Cognitive Complexity Analyzer (scc)

I've been working on a tool called Swift Cognitive Complexity Analyzer (or scc for short) — a command-line tool that calculates cognitive complexity scores for Swift and SwiftUI source files.

What is Cognitive Complexity?

You've probably heard of cyclomatic complexity — it counts the number of independent paths through your code. It's useful for testing but it has a big problem: it doesn't reflect how hard the code is to understand. A switch with 10 cases gets a similar cyclomatic score as a deeply nested loop with conditionals — yet the nested loop is clearly harder to read.

Cognitive complexity fixes this. It was created by G. Ann Campbell at SonarSource and it measures how difficult a piece of code is for a human to understand. The key idea is simple — nesting is penalized. An if inside a for inside another if costs more than three flat if statements. At the same time, things like switch (as a whole) or nil-coalescing (??) are treated as easy to read and are scored lightly or not at all.

Why should you care? Because we spend most of our time reading code, not writing it. High cognitive complexity means more bugs, slower code reviews, and harder onboarding. Keeping it low makes your codebase healthier. And in the age of AI coding agents — they also struggle more with deeply nested, complex control flow. Lower cognitive complexity likely means better results from your AI tools too.

What Swift Cognitive Complexity Analyzer Does

scc analyzes your Swift files and reports the cognitive complexity of each function. You can use it locally or plug it into your CI pipeline as a GitHub Actions PR quality gate — it supports inline annotations and PR comments.

It has two main modes: analyze for scanning files and diff for comparing complexity against a base branch. There's also a SwiftUI-aware mode which is nice — it doesn't penalize the natural nesting of SwiftUI layout containers like VStack or HStack while still catching real branching complexity.

Output formats include plain text, JSON, GitHub annotations, and markdown tables. You can set warning and error thresholds and use --violations-only to see just the functions that need attention.

How It Works

Under the hood, Swift Cognitive Complexity Analyzer uses Apple's SwiftSyntax library. SwiftSyntax is a pure-Swift parser that builds a full syntax tree from Swift source code — no compiler dependency needed. The core of the tool is a SyntaxVisitor subclass that walks the tree, tracks nesting depth, and calculates the score based on the rules from the SonarSource white paper.

The tool is written in Swift 6.0 and uses SwiftPM. It runs on both macOS and Linux.

Attribution

This tool implements the cognitive complexity metric as described by G. Ann Campbell in the SonarSource white paper (v1.7, 2023) and the ACM conference paper.

This is an independent project, not affiliated with or endorsed by SonarSource.