Can't react to the state of a class instance? #3

Open
opened 2025-10-14 15:43:09 -06:00 by navan · 0 comments
Owner

Originally created by @iwa on 6/24/2025

hello,

first let me prephrase that i'm a Swift newbie so it might just be a misunderstanding and skill issue

i'm trying to centralize my app state into its own class, so i can provide methods to mutate the data all over my app

tried to do something like below, but the app does not respond to the buttons input

am i doing something wrong or is it not possible / intended cause bad practice?

    @State var appState = AppState()

    var body: some View {
        content
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        .border(.rounded)
    }

    private var content: some View {
        VStack {
            ForEach(appState.getTodoList(), id: \.id) { todo in
                HStack {
                    Text(" [\(todo.completed ? "x" : " ")] \(todo.id) - \(todo.title)")
                    Spacer()
                    Button("Complete") {
                        if let index = appState.getTodoList().firstIndex(where: { $0.id == todo.id }) {
                            appState.toggleTodoCompletion(at: index)
                        }
                    }
                    Button("Remove") {
                        if let index = appState.getTodoList().firstIndex(where: { $0.id == todo.id }) {
                            appState.removeTodo(at: index)
                        }
                    }
                }
            }
        }
    }
*Originally created by @iwa on 6/24/2025* hello, first let me prephrase that i'm a Swift newbie so it might just be a misunderstanding and skill issue i'm trying to centralize my app state into its own class, so i can provide methods to mutate the data all over my app tried to do something like below, but the app does not respond to the buttons input am i doing something wrong or is it not possible / intended cause bad practice? ```swift @State var appState = AppState() var body: some View { content .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .border(.rounded) } private var content: some View { VStack { ForEach(appState.getTodoList(), id: \.id) { todo in HStack { Text(" [\(todo.completed ? "x" : " ")] \(todo.id) - \(todo.title)") Spacer() Button("Complete") { if let index = appState.getTodoList().firstIndex(where: { $0.id == todo.id }) { appState.toggleTodoCompletion(at: index) } } Button("Remove") { if let index = appState.getTodoList().firstIndex(where: { $0.id == todo.id }) { appState.removeTodo(at: index) } } } } } }
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: github/SwiftTUI#3
No description provided.