Eric Phillips
Eric Phillips

Reputation: 507

Non-case-sensitive switch statement in swift?

I'm playing around with an app that takes in user input, and prints a simple output.

My code looks like this:

switch text {
        case "Hi", "hi", "Hello", "hello", "Good day", "good day":
            return "Hello, sir."
        default:
            return "Sorry, I didn't understand!"
}

My question is, instead of having 5-10 possible inputs for one output, is it possible to put one input that isn't case sensitive? For example, could I just put "hello", and have my statement check for "Hello", "hello", "HELLO", etc.?

Upvotes: 4

Views: 4465

Answers (3)

Guillermo Suárez
Guillermo Suárez

Reputation: 158

The most elegant solution would be to use the lesser known String.CompareOptions in combination with .range(of:, options:). This allows you to perform much complex operations with less effort, such as matching ignoring special characters, not only case and the use of regular expression (which would be of great advantage for your specific purpose). If you don't know what they are, I recommend you look into it.

Back to topic: You can read more about String.CompareOptions here. The documentation is for NSString, but these are available for String, too.

You would then use it as follows:

let userInput = "HeLLö, how are you doing? Greetings!"

let acceptedWords = ["hello", "hi", "greeting"]

var resultCommants = acceptedWords.filter { (word) -> Bool in
    return userInput.range(of: word, options: [.caseInsensitive, .diacriticInsensitive]) != nil
}

// resultCommands = ["hello", "greeting"]

As you can see, HeLLö matches hello and Greetings matches greeting because of .caseInsensitive and .diacriticInsensitive.

If you're not familiar with the .filter operator, it iterates through your array and, for each item word, expects you to return either true or false, depending on if the item should be included in the filtered version of your array. Here this is done by comparing the result of .range(of:, options:) to nil. Unequal nil means the word was found, equal nil if not. You could of course use the range, if you wanted to know where the word was found.

Upvotes: 5

Marco Santarossa
Marco Santarossa

Reputation: 4066

An alternative solution:

func check(input: String) -> Bool {
    let strings = ["Hi", "hi", "Hello", "hello", "Good day", "good day"]

    let inputLowercase = input.lowercased()
    return strings.first(where: { $0.lowercased() == inputLowercase }) != nil
}

Upvotes: 2

Kevin Amiranoff
Kevin Amiranoff

Reputation: 14523

You could uppercase text (or lowercase [lowercased()] as mentioned in the comments), so case would not matter:

switch text.uppercased() {
case "HI", "HELLO", "GOOD DAY":
  return "Hello, sir."
default:
  return "Sorry, I didn't understand!"
}

Upvotes: 12

Related Questions