How to conditionally set TabView's $selection

I have my app set up with tab navigation using TabView(selection: $selection) to a defaulted view. What I would like to do is set this up so that if a condition is not met, that the user is directed to another view within the tab navigation.

Any suggestions or help will be greatly appreciated!


struct TabNavigationView: View {
    @AppStorage("city") var city: String?
    @State var selection: String = "Today"
 
    var body: some View {
        TabView(selection: $selection) {
            ChartView()
                .tabItem {
                    Image(systemName: "star.fill")
                        .imageScale(.large)
                    Text("Today")
                }

        NavigationView {
                LocationView()
            }
            .tabItem {
                Image(systemName: "mappin.and.ellipse")
                    .imageScale(.large)
                Text("Location")
            }
        }
    }
}
Answered by mbain108 in 626940022
Thanks to both. I incorporated the enums and populated the tag with them. Then I added logic within onAppear() . It works like a charm!
Please try something like this:
Code Block
struct TabNavigationView: View {
@AppStorage("city") var city: String?
@State var selection: String = "Location"
//@Binding var selection: String
var body: some View {
TabView(selection: $selection) {
ChartView()
.tabItem {
Image(systemName: "star.fill")
.imageScale(.large)
Text("Today")
}
.tag("Today") //<-
NavigationView {
LocationView()
}
.tabItem {
Image(systemName: "mappin.and.ellipse")
.imageScale(.large)
Text("Location")
}
.tag("Location") //<-
}
}
}

As far as tried, TabView(selection:) works when tag(_:) is specified. You can use @Binding or a Binding to a property of an EnvironmentObject, or any Binding you like, for selection:.
Try with this modifier:

Code Block
.onChange(of: selection) { value in
if value == condition {
// do something
}
}

Accepted Answer
Thanks to both. I incorporated the enums and populated the tag with them. Then I added logic within onAppear() . It works like a charm!
How to conditionally set TabView's $selection
 
 
Q