Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operator '===' cannot be applied to operands of type 'Any?' and 'UIBarButtonItem!'

Tags:

swift

swift3

The following code used to be able to compile in swift 2.2, no longer in swift 3.0. How do we fix this?

Error: Binary operator '===' cannot be applied to operands of type 'Any?' and 'UIBarButtonItem!'

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if sender === saveButton { // Error!
        // ... 
    } else if sender === closeButton { // Error!
        // ...
    }
}
like image 667
Yuchen Avatar asked Sep 17 '16 21:09

Yuchen


2 Answers

As the error message is saying. In Swift 3, Objecitve-C id is imported as Any, and you cannot call any operations for Any including ===, without explicit cast.

Try this:

if sender as AnyObject? === saveButton {

(All the same for other sender comparison.)

And remember, in Swift 3, as AnyObject has become one of the most risky operations, you should not use as AnyObject in other cases.

like image 102
OOPer Avatar answered Oct 18 '22 21:10

OOPer


Try using optional binding with conditional cast to establish the type of the item before comparing:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let sender = sender as? UIBarButtonItem, sender === saveButton {
        // ...
    } else if let sender = sender as? UIBarButtonItem, sender === closeButton {
        // ...
    }
}
like image 37
vacawama Avatar answered Oct 18 '22 22:10

vacawama