SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

`inert_defer` should ignore `init`

Open lhunath opened this issue 4 years ago • 0 comments

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

lhunath avatar Aug 04 '21 05:08 lhunath