在swift中使switch不区分大小写
我已经为用户提供了一种简单的方法,让他们在控制台中键入一些选项来进行选择在swift中使switch不区分大小写,swift,switch-statement,case,case-sensitive,case-insensitive,Swift,Switch Statement,Case,Case Sensitive,Case Insensitive,我已经为用户提供了一种简单的方法,让他们在控制台中键入一些选项来进行选择 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 "sub
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
func trimNonalphas(_ s: String) -> String {
return s.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}
switch trimNonalphas(chooseWisely.lowercased()) { // ...
匹配是
,是
,是
,等等的再往前走。例如,如果您愿意接受“yes!”和“yes”,请在比较之前将标点符号去掉choose
。例如:
let chooseWisely = // whatever
switch chooseWisely.lowercased() {
case "ye", "yup", "yes", "y", "yeah", "yeya", "yes!", "both" :
// ... and so on
func trimNonalphas(_ s: String) -> String {
return s.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}
switch trimNonalphas(chooseWisely.lowercased()) { // ...
现在“Yes!”与“Yes”匹配,依此类推。免费打字通常不合适。您应该尝试他们可以选择的数字答案,而不是键入。如果你想让他们输入,就像@matt说的那样,你可以让他们的响应小写,并对照小写字符串进行检查。您可以为每个问题创建一个包含一组答案的数组,然后使用contains方法查看其答案是否包含在数组中。如果不是,你可以提示他们写另一个答案。谢谢@WaylanSands我有同样的感觉,但我还没有开始学习SwiftUI,我不知道如何让人们在控制台中选择。我想象一旦我开始开发前端,这将不再是一个问题。