在 swift 中使 switch case 不区分大小写

Making switch cases case-insensitive in swift

我为用户提供了一种简单的方法,让用户可以在控制台中键入以在几个选项之间进行选择。

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.")
}

如您所见,这些案例在试图涵盖大量可能的用户输入时变得非常笨拙,我至少想通过使其不区分大小写来简化它。

如果我从一开始就走错了路,我也愿意接受一种完全不同的处理用户输入的方法。

首先处理标签(比较对象), 比较之前,使其与您愿意接受的内容相匹配。例如:

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

匹配 yesYESYes 等。 ——然后走得更远。例如,如果您愿意接受 "yes!" 和 "yes",请在 比较之前去除标点符号 chooseWisely 。例如:

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

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

现在 "Yes!" 匹配 "yes",依此类推。