Filter SwiftUI object Array

Viewed 33

I'd like to filter an array of object if the todoStatus === true and then return the count but I am unsure of how to go about it,I can already get the count of the entire array, but I'm not sure how to filter it down.

Here is what the structure looks like:

class ToDo: ObservableObject, Identifiable {
    var id: String = UUID().uuidString
    @Published var todoName: String = ""
    @Published var todoStatus: Bool = false
    
    init (todoName: String, todoStatus: Bool) {
        self.todoName = todoName
        self.todoStatus = todoStatus
    }
}

class AppState: ObservableObject {
    @Published var todos: [ToDo] = []
    init(_ todos: [ToDo]) {
        self.todos = todos
    }
}

struct ContentView: View {
    var name = "Leander"
    
    @ObservedObject var state: AppState = AppState([
         ToDo(todoName: "Wash the Dogs", todoStatus: true),
         ToDo(todoName: "Wash the Dogs", todoStatus: false),
         ToDo(todoName: "Wash the Dogs", todoStatus: true),
         ToDo(todoName: "Wash the Dogs", todoStatus: false),
         ToDo(todoName: "Wash the Dogs", todoStatus: true),
         ToDo(todoName: "Wash the Dogs", todoStatus: false),
        ])

and how I'm accessing the count

                       Text("\($state.todos.count)")
2 Answers

You would simply use the .filter function on Array, then .count it like this:

let todoStatusCount = state.todos.filter( { $0.todoStatus } ).count

try this simple code, no need for the $state, just state, and no need for the $0.todoStatus == true:

  Text("\(state.todos.filter{$0.todoStatus}.count)")

Note, you should not nest ObservableObject, like you do, that is, class AppState: ObservableObject containing an array of class ToDo: ObservableObject. Use

struct ToDo: Identifiable {
    let id: String = UUID().uuidString
    var todoName: String = ""
    var todoStatus: Bool = false
}
Related