0

I am filtering an array based on a set filter supplied to the view (this filter varies) but want to modify the function to allow for an empty filter, i.e return the original array un filtered. I feel like this should be a simple matter but I'm currently a bit lost - have looked at the .isEmpty modifier and a couple of different IF statements but I'm not "getting it"

    var categoryFilter:String

var filteredCategoryTasks: [Task] {
    modelData.tasks.filter { task in
        (task.category == categoryFilter)
}
}
2
  • Maybe this might help: stackoverflow.com/q/65497054/14351818 Commented Jun 20, 2021 at 23:08
  • This is a Swift question, not SwiftUI -- I've edited the title/tags to reflect that. Commented Jun 20, 2021 at 23:10

1 Answer 1

0

You could return the original array in the event that the String is empty and the filtered array otherwise:

var filteredCategoryTasks: [Task] {
    categoryFilter.isEmpty ? modelData.tasks : modelData.tasks.filter { task in
          (task.category == categoryFilter)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer your question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.