swiftuiswiftui-state

Why does the state change back to original state?


I'm new to SwiftUI and I couldn't understand why the selectedUser is set to nil on the fullScreenCover block. Note that User is a class from a third party library and doesn't conform to ObservableObject

struct Users: View {
    
    @State private var isUserSelected = false
    @State private var shouldPresentCallScreen = false
    @State private var selectedUser: User? = nil {
        didSet {
            isUserSelected = selectedUser != nil
            
            shouldPresentCallScreen = isUserSelected
        }
    }
    
    var body: some View {
        UserListView(
           onUserSelected: { user in
               //user is not nil here. 
               selectedUser = user
           }
        )
        .fullScreenCover(isPresented: $shouldPresentCallScreen) {
            //shouldPresentCallScreen is false and
            //selectedUser is null here.
            UserDetail(user: selectedUser)
        }
    }
}

Edit: When I set selectedUser to a non-nil value initially, It works as expected. But I still don't understand why.

selectedUser: User? = User(.....)


Solution

  • The reason is you didn't call the selectedUser getter anywhere in body so it didn't think you cared about the updated value. The reason it thinks that is because the source of truth was wrongly designed, cool you fixed it, item: is a good option.

    It's best to have one state source of truth and use it for selection and presenting, ie remove the extra bool. E.g. fullScreenCover(item: , content:)