string - 使用 ||对于 swift 中 if 语句中的多个字符串

标签 string swift foundation command-line-tool

我正在制作一个命令行 Swift 应用程序,我有一个用户提示,用户可以在其中回答"is"并继续或进行其他任何操作并退出。但我在想,如果有人回答“y”或“YES”或“Yes”或“yEs”怎么办。我试过使用 ||但显然这仅适用于整数。

这是我的代码:

var askNewFile = getInput()
    if askNewFile == ("yes") {
        //code to start blank editor
    }
    else {
        print("Bye!")
        exit(1)
    }

我将不胜感激任何帮助,甚至向正确的方向插入。

最佳答案

将所有表示"is"的单词放入一个数组中,并对用户的输入进行不区分大小写的搜索:

let isYes =  ["y", "yes", "yeah", "yup"].contains {
    askNewFile.compare($0, options: [.CaseInsensitiveSearch]) == .OrderedSame
}
if isYes {
    // User answered yes
}

关于string - 使用 ||对于 swift 中 if 语句中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966562/

相关文章:

ios - 是否有任何公共(public) API 可以检测 iOS 16(beta 3)中的锁定模式?

identity - 查找 Windows Identity Foundation 的 STS 提供程序

c# - 格式化以下字符串的最有效方法是什么?

ios - 无法在我的 iOS 应用程序中读取 XML 文件

ios - 如何快速进行多问题测验,以免问题重复出现?

ios - iAd 横幅在 segue 上变白

c++ - lib clang.dylib : change installation path

python:如何计算两个单词列表的余弦相似度?

C编程 "weird output"

string - Bash 将数据集拆分为每对 1 行