使用 ||对于 swift 中 if 语句中的多个字符串
Using || for multiple strings in an if statement in swift
我正在制作一个命令行 Swift 应用程序,我有一个用户提示,用户可以在其中回答 "yes" 并继续或其他任何内容并退出。但我在想,如果有人回答 "y" 或 "YES" 或 "Yes" 或 "yEs" 怎么办?我试过使用 ||但显然这仅适用于整数。
这是我的代码:
var askNewFile = getInput()
if askNewFile == ("yes") {
//code to start blank editor
}
else {
print("Bye!")
exit(1)
}
我将不胜感激任何帮助,甚至向正确的方向推动。
将所有表示 "yes" 的词放入一个数组中,并对用户的输入进行不区分大小写的搜索:
let isYes = ["y", "yes", "yeah", "yup"].contains {
askNewFile.compare([=10=], options: [.CaseInsensitiveSearch]) == .OrderedSame
}
if isYes {
// User answered yes
}
或者,如果您希望能够使用仅包含字符串值的 OR 条件,您可以尝试以下公式
let animal = "Fox"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
您需要记住在要测试的每个新字符串值之前放置原始值和 ==,在本例中为:'animal'
我正在制作一个命令行 Swift 应用程序,我有一个用户提示,用户可以在其中回答 "yes" 并继续或其他任何内容并退出。但我在想,如果有人回答 "y" 或 "YES" 或 "Yes" 或 "yEs" 怎么办?我试过使用 ||但显然这仅适用于整数。
这是我的代码:
var askNewFile = getInput()
if askNewFile == ("yes") {
//code to start blank editor
}
else {
print("Bye!")
exit(1)
}
我将不胜感激任何帮助,甚至向正确的方向推动。
将所有表示 "yes" 的词放入一个数组中,并对用户的输入进行不区分大小写的搜索:
let isYes = ["y", "yes", "yeah", "yup"].contains {
askNewFile.compare([=10=], options: [.CaseInsensitiveSearch]) == .OrderedSame
}
if isYes {
// User answered yes
}
或者,如果您希望能够使用仅包含字符串值的 OR 条件,您可以尝试以下公式
let animal = "Fox"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
您需要记住在要测试的每个新字符串值之前放置原始值和 ==,在本例中为:'animal'