我做了一个简单的方法,让用户输入控制台来选择几个选项。
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
这符合... yes
, YES
, Yes
,等等。- 再进一步。例如,如果你愿意接受 "是的!"和 "是的",就把标点符号去掉。chooseWisely
之前 的比较。例如:"是的!"匹配 "是的"。
func trimNonalphas(_ s: String) -> String {
return s.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}
switch trimNonalphas(chooseWisely.lowercased()) { // ...
现在 "是的!"匹配 "是的",以此类推。