Search code examples
swiftswift4

Adding a filter to an array in Swift 4


I have a struct, which is my data model:

import Foundation

struct Item : Codable {

var cat:String
var name:String
var createdAt:Date
// more 
var itemIdentifier:UUID
var completed:Bool

func saveItem() {
    DataManager.save(self, with: itemIdentifier.uuidString)
}

func deleteItem() { DataManager.delete(itemIdentifier.uuidString)
}

mutating func markAsCompleted() {
    self.completed = true
    DataManager.save(self, with: itemIdentifier.uuidString)
}

}

Then in my ViewController I have the following code to load the data, which goes into a TableView (sorted by the creation date).

func loadData() {
    items = [Item]()
    items = DataManager.loadAll(Item.self).sorted(by: {
        $0.createdAt < $1.createdAt })
    tableView.reloadData()
}

Now I would like to add a filter, so that only category goes into the TableView. For instance, only where cat equals "garden".

How can I add that?


Solution

  • Use filtered.

    Here is an example of your unfiltered array:

    var unfilteredItems = ...
    

    Here is a filtering code:

    var filteredItems = unfilteredItems.filter { $0.cat == "garden" }
    

    Here is the code:

    func loadData() {
        items = [Item]()
        items = DataManager.loadAll(Item.self).sorted(by: {
            $0.createdAt < $1.createdAt }).filter { $0.cat == "garden"}
    
        tableView.reloadData()
    }