realm / realm/SwiftLint

Rule Request: Optional Property Write

Open
#1,519 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

rule-request
Dominant language
Swift
Stars
19.7k
Forks
2.3k
Avg merge
1d 1h
Merged PRs (30d)
11

Description

This is a rule request. I'm willing to implement this myself and send a PR, but before doing that I'd like to know if the rule is wanted or not. To explain the desired rule, I'd like to first post the custom rule we are already using in our projects:

optional_property_write:
    included: ".*.swift"
    regex: '\S+!\.\S+\s*=[^=]\s*'
    name: "Writing Properties on Optionals"
    message: "Don't use ! to write into properties on optionals – use ? instead."
    severity: warning

I felt like this rule might be useful for other projects as well, which is why I'm posting it. What do you think about it? For us it helps a lot to prevent common issues and enforce a shared style.

Rationale

When assigning a value to a property of a type, some people used the ! syntax which will lead to a crash. In nearly all cases it is better to use ? instead to ensure the app doesn't crash due to this single property assignment. In cases where the existence of the variable is required, the if let or guard let syntax should be used anyways.

A few examples:

let label: UILabel?

// ❌ not acceptable
label!.text = "someString"

// ✅ acceptable
label?.text = "someString"

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the custom optional_property_write YAML rule and the Swift examples in the issue, then read the existing discussion for the maintainers' decision. Done means the project has decided whether to accept this rule; implementation scope and tests are not specified here.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.