-1

I've made a simple way for a user to type in console to choose between a few options.

print("Y / N / SUBS / SCENES")
let chooseWisely = readLine()

switch chooseWisely{
  case "Y","ye","yup","yes","y","YES","Yeah","yeya","YES!","Yes","Yup","Both","both":
    print(Alrighty, doing both)

  case "subs", "just subs", "only subs", "subs only", "Subs", "subywuby", "subway", "SUBS":
    print("okay, just subs")

  case "scenes", "Scenes", "shits", "sceneeruskies", "just scenes", "scenes only", "only scenes", "scenes fired", "scenes!", "SCENES", "gimmeh the scenes":
    print("okay, just scenes")

  case .some(_):
    print("Alrighty then, not doing it.")

  case .none:
    print("Alrighty then, not doing it.")
}

As you can see the cases get quite unwieldy trying to cover a decent amount of possible user inputs, I would at least like to simplify it by making it case insensitive.

I'm also open to an entirely different approach of handling user input like this if I've gone down the wrong path from the get go.

matt
  • 515,959
  • 87
  • 875
  • 1,141
Johnson
  • 161
  • 9
  • 1
    Free typing usually isn't the go. You should try figure answers that they can select, not type. If you want to allow them to type, like @matt said you could make their response lowercase and check that against lower case strings. you could make an array for each question with a set of answers and then use the contains method to see if their answer is contained within the array. If it's not you could prompt them to write another answer. – Waylan Sands May 22 '20 at 13:06
  • Thanks @WaylanSands I have the same feeling, but I haven't started learning SwiftUI yet and I can't figure out how to have people select in the console. I imagine once I start developing a front end that this will no longer be an issue. – Johnson May 22 '20 at 13:56

1 Answers1

1

Process the tag (the comparand) first, before the comparison, so that it matches what you're willing to accept. For example:

let chooseWisely = // whatever
switch chooseWisely.lowercased() {
case "ye", "yup", "yes", "y", "yeah", "yeya", "yes!", "both" :
    // ... and so on

That matches yes, YES, Yes, and so on. — And go further. For example, if you are willing to accept "yes!" and "yes", strip punctuation off chooseWisely before the comparison. For example:

func trimNonalphas(_ s: String) -> String {
    return s.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}

switch trimNonalphas(chooseWisely.lowercased()) { // ...

Now "Yes!" matches "yes", and so on.

matt
  • 515,959
  • 87
  • 875
  • 1,141