realm / realm/SwiftLint

Rule proposal: Return before defer

Open
#1,358 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

I had code of the form:

let semaphore: DispatchSemaphore(value: 0)
asyncCall(..., completionHandler: { _ in
	if flag { return }
	defer { semaphore.signal() }
	...
})
semaphore.wait()

I added the early return some while after the defer, and it never triggered (it's a rather obscure check in test code). This, of course, livelocks if flag is true -- a small oversight, but it took a while to find.

The problem is that at first sight, the code is fine: defer makes sure that no matter how the function returns, the semaphore is signalled -- well, only those returns below.

Hence, I propose a warning for returns that come before defers, or the other way around.

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 with the Swift example in the issue and determine the intended warning for returns that occur before a defer. No files or tests are named, so the next step is to locate SwiftLint’s rule implementation and testing conventions. Done means the proposal’s problematic pattern is diagnosed consistently and covered by tests.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.