0

I'm making a command line Swift app and I have a user prompt where users can answer "yes" and proceed or anything else and exit. But I was thinking what if someone answers "y" or "YES" or "Yes" or "yEs". I've tried using || but apparently that is only for ints.

This is my code:

var askNewFile = getInput()
    if askNewFile == ("yes") {
        //code to start blank editor
    }
    else {
        print("Bye!")
        exit(1)
    }

I would appreciate any help, or even nudges in the right direction.

2 Answers2

3

Put all the words that mean "yes" into an array and do a case-insensitive search on the user's input:

let isYes =  ["y", "yes", "yeah", "yup"].contains {
    askNewFile.compare($0, options: [.CaseInsensitiveSearch]) == .OrderedSame
}
if isYes {
    // User answered yes
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
0

Or if you wanted to be able to use the OR conditional with String only values you could try the following formula

let animal = "Fox"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}

You need to remember to put the originating value and == before each new String value you want to test, in this case: ' animal '

David_2877
  • 257
  • 4
  • 7