1

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)")
0

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for the feedback and insight, I will definitely implement that now
if my answer helped, could you mark it as accepted please, using the tick mark, it turns green.
1

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.