How to call an optional function using Selector and NotificationCenter

Viewed 349

Language: Swift 3

IDE: XCode 8.3.2 (8E2002)

I have a protocol with an optional function foo

@objc protocol SomeProtocol {
    @objc optional func foo(_ notification: Notification)
}

extension SomeProtocol {
    func listenToFoo() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.foo(_:)), name: NSNotification.Name(rawValue: "UltimateNotificationKeyLOL"), object: nil)
    }
}

If I extend this code to a class, say a UIViewController.

class CrashingViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        self.listenToFoo()
    }
}

extension CrashingViewController: SomeProtocol { } 

Now here comes the problem, since foo is an optional function, if any one sends a Notification with the key NSNotification.Name(rawValue: "UltimateNotificationKeyLOL") the application will crash because I haven't implemented foo yet. So in this case, the above code will cause a crash.

However if I do this

class GodzillaViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        self.listenToFoo()
    }
}

extension GodzillaViewController: SomeProtocol {
    func foo(_ notification: Notification) {
        print("lol")
    }
} 

No crash is created since foo(_:) is not optional anymore.

Also: This code isn't possible #selector(self.foo?(_:))

Question: Is it possible to have a selector call an optional function without crashing the application?

1 Answers
Related