Search code examples
swiftuistatedefault

SwiftUI - State without an initial value


I have a state declared in my view

@State var selected: Bool = false
@State var selectedPerson: Person

When a "Person" is selected from a view there is a callback that sets the "selected" state to true, and sets the person that is selected:

MapView(viewModel: MapViewModel(people: viewModel.people)) { value in
     selectedPerson = viewModel.getPersonWith(name: value.title)
     selected = true
}

When all of this is set, it triggers a NavigationLink like this:

NavigationLink(destination: PersonDetailsView(viewModel: PersonViewModel(person: selectedPerson)), isActive: self.$selected) {
      EmptyView()
}.hidden()

Everything works fine, but I have to set a default value to the "selectedPerson" state before the struct is initialized, even tho there is no person selected. Is there a way to bypass this, without giving the "selectedPerson" state a default "dummy" value. Thanks :)


Solution

  • You need to make initial state optional, like

    @State var selectedPerson: Person?
    

    but as well you have to handle this optional in all places that use it, like

    if nil != selectedPerson {
       NavigationLink(destination: 
          PersonDetailsView(viewModel: PersonViewModel(person: selectedPerson!)), // << !!
                                  isActive: self.$selected) {
          EmptyView()
       }.hidden()
    }