简体   繁体   中英

Swift array filter with empty filter value

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, ie 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)
}
}

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM