PixelStack PixelStack - 6 days ago 4x
Swift Question

Cannot convert value of type 'UIBarButtonItem!' to expected argument type '_OptionalNilComparisonType'

I'm trying to follow the FoodTracker tutorial on Apple Developer. Right now I'm on the section "Implementing Navigation".

It looks like this tutorial was written for a previous version of Swift as the code doesn't work sometimes without having to change overridden method signatures.

Here's an example:

// This method lets you configure a view controller
// before it's presented.
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?) {

On my version of Xcode (8.0) that method has to change to:

override func prepare(for: UIStoryboardSegue, sender: Any?)

...so that it matches the appropriate method in the parent class/protocol that needs to be overridden.

The tutorial continues with the following line of code:

if saveButton == sender {

...which produces the error on the subject line.

I have spent the last few hours trying to fix this, searching online, trying to figure out why the optional sender Any? doesn't match a UIBarButtonItem but have been unsuccessful, so as a last resort I am posting here. I have been attempting to follow a couple of books on iOS development, but I was running into problems with the code as well (doesn't work in the current version of Xcode(8.0)/Swift(3), so I decided to spend time on the official Apple tutorial.

Thanks in advance for any help you can provide.

ohr ohr

Have you tried casting your sender (Any?) as a UIBarButtonItem?

if saveButton == (sender as? UIBarButtonItem)