realm / realm/SwiftLint

`inert_defer` should ignore `init`

Open
#3,687 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

New Issue Checklist
Describe the bug

Within init functions, the defer at the end is not necessarily a no-op, since there is in fact a behavioural difference between putting code in a defer or outside of a defer at the end of an init function; specifically, assigning to a type's properties from within an init will not trigger that properties' willSet/didSet hooks, while performing the same assignment from within a defer inside init will trigger them. Therefore, it is a valid pattern to use defer at the end of init in order to force firing the property change handlers.

Complete output when running SwiftLint, including the stack trace and command used
$ swiftlint lint --path test.swift
Linting Swift files at paths test.swift
Linting 'test.swift' (1/1)
/Users/lhunath/workspace/lyndir/Spectre/ios/test.swift:11:9: warning: Inert Defer Violation: If defer is at the end of its parent scope, it will be executed right where it is anyway. (inert_defer)
Done linting! Found 1 violation, 0 serious in 1 file.
Environment
  • SwiftLint version (run swiftlint version to be sure)? 0.43.1
  • Installation method used (Homebrew, CocoaPods, building from source, etc)? Homebrew
  • Which Xcode version are you using (check xcodebuild -version)? Xcode 12.5.1 Build version 12E507
class Test {
    var test: String? {
        didSet {
            print("self.test => \(self.test!)")
        }
    }

    init() {
        self.test = "a"

        defer {
            self.test = "b"
        }
    }
}

_ = Test()
$ ./test
self.test => b

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 locating the inert_defer rule and its tests, then reproduce the reported Swift example to confirm the diagnostic. The work is done when a defer at the end of an init is ignored by this rule, while the rule's behavior for other parent scopes remains covered by regression tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.