TabView init(selection:content:) in Xcode 14.3.1

Hi,

I have the following code snippet. If I use binding selection in the view model, when I release the swipe gesture, it goes back to "Tab 1", and the "selectedTab" doesn't seem to update automatically. But if I use binding optional selection in the view, then it works as expected. Could someone help me clarify it?

struct TabModel: Identifiable, Hashable {
    let id: Int
    let name: String
}

class TabViewModel: ObservableObject {
    // tabview binding selection
    @Published var selectedTab: TabModel? 
    var tabs: [TabModel]

    init() {
        tabs = [
            TabModel(id: 1, name: "Tab 1"),
            TabModel(id: 2, name: "Tab 2"),
            TabModel(id: 3, name: "Tab 3")
        ]
    }
}

struct ContentView: View {
    @ObservedObject var viewModel: TabViewModel
    // tabview binding selection
    @State private var selectedTab: TabModel?

    var body: some View {
        TabView(selection: $viewModel.selectedTab/$selectedTab) {
            ForEach(viewModel.tabs) { tab in
                Text(tab.name)
                    .tag(tab)
            }
        }
        .tabViewStyle(.page)
    }
}

Could you post the 2 codes: the one that works, the one that fails. That will make it much easier to analyse.

TabView init(selection:content:) in Xcode 14.3.1
 
 
Q