Seong Lee Seong Lee - 7 months ago 21
Swift Question

If filter returns nil, how do I not return empty result?

I'm doing the following filtering that returns a recipe list, filtered by given category name value.

filteredRecipe = filteredRecipe.filter({
if let category = $0.valueForKey("category") as? NSManagedObject {
if let name = category.valueForKey("name") as? String {
return name.rangeOfString(cap) != nil
} else {
return false
}
} else {
return false
}
})


This filter works in association with searchBar textfield so I will possibly have random value in the textfield which will make
filteredRecipe
to hold unreliable data.

I need to make sure when the filter can't find any recipe from
filteredRecipe
with given category name value, I leave
filteredRecipe
untouched.
Currently, when there is no match, it makes
filteredRecipe
empty array
[]
. I'm not sure what part causes this.

Answer

You need to assign the filtering result to a temporary variable and check that it isn't empty.

let filtered = filteredRecipe.filter({
    if let category = $0.valueForKey("category") as? NSManagedObject {
        if let name = category.valueForKey("name") as? String {
            return name.rangeOfString(cap) != nil
    } 
    return false
})

if !filtered.isEmpty {
    filteredRecipe = filtered
}
Comments