How do I set an @State variable programmatically in SwiftUI

Example of how I set initial state values in one of my views:

struct TodoListEdit: View {
    var todoList: TodoList
    @State var title = ""
    @State var color = "None"

    init(todoList: TodoList) {
        self.todoList = todoList
        self._title = State(initialValue: todoList.title ?? "")
        self._color = State(initialValue: todoList.color ?? "None")
    }

Joe Groff: "@State variables in SwiftUI should not be initialized from data you pass down through the initializer. The correct thing to do is to set your initial state values inline:"

@State var selectedTab: Int = 1

You should use a Binding to provide access to state that isn't local to your view.

@Binding var selectedTab: Int

Then you can initialise it from init and you can still pass it to child views.

Source: https://forums.swift.org/t/state-messing-with-initializer-flow/25276/3

Tags:

Swiftui