Swift 2 crashing on where clause inside if-let

Converting my app to use Swift 2, and I'm getting a crash on this if-let where clause (that worked in 1.2):


Used to look like this:

if showFilterButton {
    if let dataController = dataController() as? FilteredCoreDataController, filter = dataController.filter where filter.customized {
        filterButton = UIBarButtonItem(image: UIImage(named: "FilterFilled"), style: .Plain, target: self, action: "showFilters:")
    } else {
        filterButton = UIBarButtonItem(image: UIImage(named: "Filter"), style: .Plain, target: self, action: "showFilters:")
    }
} else {
    filterButton = nil
}

But it crashes on line 2. Finally discovered that removing the where clause doesn't crash the app (but obviously doesn't give me the behavior I want). Thought it was something weird like Apple changing how where clauses with in an if-let clause, but even separating it out into a nested if doesn't work:

if showFilterButton {
    if let dataController = dataController() as? FilteredCoreDataController, filter = dataController.filter {//where filter.customized {
        if filter.customized {
            filterButton = UIBarButtonItem(image: UIImage(named: "FilterFilled"), style: .Plain, target: self, action: "showFilters:")
        } else {
            filterButton = UIBarButtonItem(image: UIImage(named: "Filter"), style: .Plain, target: self, action: "showFilters:")
        }
    } else {
        filterButton = UIBarButtonItem(image: UIImage(named: "Filter"), style: .Plain, target: self, action: "showFilters:")
    }
} else {
    filterButton = nil
}

Crashes on line 3 with an EXC_BAD_ACCESS (code=2, address = 0x6060000e1bc0)


I thought once you do the optional binding, you can use that variable/constant in subsequent bindings, which is what I use to construct the filter constant. The compiler doesn't complain about me using filter in the where clause, but it still crashes at runtime without any real useful error message.


Anyone getting crashes like this? I have Address Sanitizer and zombies enabled. Should I file a bug/radar?

So I was able to fix the crash by making my filter (previously an object that implemented my Filter protocol, which declares a "customized" Bool variable) a subclass of a new (middleman) BaseFilter class I created (which in turn implements Filter). For some reason, optionally casting the filter to BaseFilter and then trying to access the customized Bool doesn't crash.


if let dataController = dataController() as? FilteredCoreDataController, filter = dataController.filter as? BaseFilter where filter.customized {

This line doesn't crash anymore after changing the class/protocol hierarchy.


Still doesn't explain why it requires filter to be a subclass instead of just implementing a protocol, kind of defeats the purpose of declaring a protocol if I can't access the variables it declares.

Swift 2 crashing on where clause inside if-let
 
 
Q