Discarded Notification Center Observer

When registering for a notification using a block, the opaque observer that is returned should be stored so it can be removed later

  • Identifier: discarded_notification_center_observer
  • Enabled by default: No
  • Supports autocorrection: No
  • Kind: lint
  • Analyzer rule: No
  • Minimum Swift compiler version: 5.0.0
  • Default configuration:
    KeyValue
    severity warning

Non Triggering Examples

let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }
let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
func foo() -> Any {
    return nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
}
func foo() -> Any {
    nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
}
var obs: [Any?] = []
obs.append(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }))
var obs: [String: Any?] = []
obs["foo"] = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
var obs: [Any?] = []
obs.append(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }))
func foo(_ notify: Any) {
   obs.append(notify)
}
foo(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }))
var obs: [NSObjectProtocol] = [
   nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }),
   nc.addObserver(forName: .CKAccountChanged, object: nil, queue: nil, using: { })
]
names.map { self.notificationCenter.addObserver(forName: $0, object: object, queue: queue, using: block) }
f { return nc.addObserver(forName: $0, object: object, queue: queue, using: block) }

Triggering Examples

nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }
_ = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }
nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
@discardableResult func foo() -> Any {
   return nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
}
class C {
    var i: Int {
        set { notificationCenter.addObserver(forName: $0, object: object, queue: queue, using: block) }
        get {
            notificationCenter.addObserver(forName: $0, object: object, queue: queue, using: block)
            return 2
        }
    }
}
f {
    nc.addObserver(forName: $0, object: object, queue: queue) {}
    return 2
}
func foo() -> Any {
    if cond {
        nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
    }
}