New article weekly. No noise. Subscribe
Thumbnail image for Contributing to SwiftLint: Enforcing Implicit Optional Initialization Style
August 13, 2025

Contributing to SwiftLint: Enforcing Implicit Optional Initialization Style

Enforcing a consistent style for initializing optional variables in SwiftLint.

I recently made a small but neat contribution to SwiftLint that just got merged. The goal was simple: enforce a consistent style for initializing optional variables without unnecessary = nil.

The Problem

Swift optionals are nil by default, so writing:

var title: String? = nil

is redundant. While it compiles fine, it’s extra noise in the codebase. I wanted a rule to ensure we follow the cleaner style:

var title: String?

SwiftLint already has a similar redundant_optional_initialization rule, but it’s intended as a correctness rule, not specifically as a style enforcement tool. The idea was to create a configurable rule that lets teams explicitly choose whether to forbid or allow the = nil form. This new rule supersedes redundant_optional_initialization.

Implementation

The rule, named implicit_optional_initialization, is built using SwiftSyntax and inspects PatternBindingSyntax nodes. It detects cases where:

Example violation:

var title: String? = nil
var count: Int? = nil

Valid code:

var count: Int?

It also correctly ignores cases where the = nil is part of a more complex declaration or has a specific reason to be explicit.

Testing

SwiftLint’s example-based testing makes it easy to add sample violations and valid cases:

// Violation
var username: String? = nil
// No violation
var username: String?

From there, the test suite automatically verifies that the rule flags violations and leaves valid cases untouched.

Lessons Learned

This was my first time working with SwiftLint’s SwiftSyntax-based rules, and I picked up a few things along the way:

Outcome

The PR was merged into SwiftLint’s main branch and will be available in an upcoming release. Teams can now opt in to implicit_optional_initialization to keep their codebases clean and consistent.

If you're still here, might as well subscribe :)

· RSS

Related Articles