is changing between view files through a swift picker possible?

Viewed 48

Having three separate files for different Views I'm trying to bring them together in a CheckerView file that's called from the main in WindowGroup. I want my picker to change views on swipes between tags as shown in CheckerView Implementation. The two other views that are currently not displayed are commented out. Correct First View Incorrect Second View.I believe I need to use enums, but am unsure how to approach this as I picked up the language very recently. I had correctly implemented a similar functionality through tabView however the picker applies better to what I am trying to do. Thanks for the help !

1 Answers

Enums are a good way to go, as they have a fixed number of possible values and can have descriptive names, both of which will help your view code more readable.

First thing to do is define an enum which declares the possible options for you:

enum ViewChoice { // you probably want a better name than this
  case palindrome, anagram, pangram
}

Then in your parent view, your state variable needs to be of this type

struct CheckerView: View {
  @State private var toView: ViewChoice = .palindrome

  // ...
}

Your picker should then use enum values in each option's tag:

Picker(..., selection: $toView) {
  Text("Palindrome").tag(ViewChoice.palindrome)
  // etc.
}

Once those changes are in place, you should have toView continuing to be updates as before, but it can only be one of three choices.

Then you can use a switch statement to include the appropriate subview:

switch(toView) {
case .palindrome:
  PalindromeView()
case .anagram:
  AnagramView()
case .pangram:
  PangramView()
}

Note that you don't have to use enums: you're currently setting toView as an integer and changing its value correctly in the Picker. So you could write a switch statement with case 0, case 1 etc. - but not only are those numbers less readable than using names, you would also have to add a default option to the switch statement, because whenever you use switch you have to account very every possible eventuality, and an integer could be some other value than 0, 1 or 2 even though those are the only values you use.

Related