Comparing Any? Object in Swift 3

Hey there,


I was following the Developing iOS Apps (Swift) Guide by Apple using Xcode 8.0 beta 6 and ran into a problem while implementing navigation:


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if sender === saveButton{
        }
    }


The comparison between the sender object (type Any?) and the saveButton (type UIBarButtonItem!) in this code does not work and yields the following error:


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


Only possible way to make it work is to downcast the sender object to the UIBarButtonItem class and compare the casted copy to saveButton. Of course, this is easy, but shouldn't the identity operator (===) still work even in Swift 3? As Apple's guide shows, it used to work in the previous version or did I miss anything?


Best wishes and thanks!

There are several changes in Swift 3 that might have made the === test meaningless. The most likely in this context is that the 'sender' parameter type changed from AnyObject? to Any?, because of a change in the way NSObject is bridged to Swift native types.


Because AnyObject and UIBarButtonItem are both reference types, they can be compared using ===. However, that operator can't be used with value types such as Any.


You have two choices:


1. You can use a downcast ('as? AnyObject' would be sufficient, though 'as? UIBarButtonItem' has the same effect).


2. You can use the regular == operator, under the assumption that the only values of 'sender' will not have a custom == operator that somehow give a weird answer, and that == between two UIBarButtonItems will use the default NSObject implementation of the 'isEqual:' method, which uses pointer equality.


The second choice is the easiest and is almost certainly safe. But if you don't like the hand-waving that declares it safe, well, the first choice is bulletproof.

Another option is to drive your logic based on the incoming segue's identifier.


And, in cases where more than different sender can trigger the same segue, perhaps use a 'tag' attribute to distiguish them.


Another option is to re-organize code a bit and implement an IBAction for your save button. In that, you can always trigger a particular segue as needed.

Comparing Any? Object in Swift 3
 
 
Q