0

Following code should print value when tab changes, But it is not printing as expected. The same code is working fine if I use the selected data type like Int or string instead of an enum.

Do I need to confirm enum to anything for making this work?

enum Tab: String, Codable, Comparable {
    static func < (lhs: Tab, rhs: Tab) -> Bool {
        lhs.rawValue < rhs.rawValue
    }
    
    case firstTab
    case secondTab
    case thirdTab
}

struct ContentView: View {
 
    @State var selected: Tab = .firstTab
    var body: some View {
        TabView(selection: $selected) {
            Text("first tab")
                .tabItem {
                    Text(Tab.firstTab.rawValue)
                }.tag(Tab.firstTab.rawValue)
               
            Text("second tab")
                .tabItem {
                    Text(Tab.secondTab.rawValue)
                }.tag(Tab.secondTab.rawValue)
            Text("third tab")
                .tabItem {
                    Text(Tab.thirdTab.rawValue)
                }.tag(Tab.thirdTab.rawValue)
        }.onChange(of: selected, perform: { value in
            print(value)
        })
    }
}

Thanks in advance

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
Sai Durga Mahesh
  • 205
  • 2
  • 13

1 Answers1

3

Remove .rawValue for each tag as your TabView use enum case for selection, not your case string (.rawValue)

TabView(selection: $selected) {
    Text("first tab")
        .tabItem {
            Text(Tab.firstTab.rawValue)
        }.tag(Tab.firstTab) //< -Here
    
    Text("second tab")
        .tabItem {
            Text(Tab.secondTab.rawValue)
        }.tag(Tab.secondTab) //< -Here
    Text("third tab")
        .tabItem {
            Text(Tab.thirdTab.rawValue)
        }.tag(Tab.thirdTab) //< -Here

Do I need to confirm enum to anything for making this work?

No. No need to confirm anything more.

Just make it simple

enum Tab: String {
    case firstTab
    case secondTab
    case thirdTab
}
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52