【问题标题】:Using || for multiple strings in an if statement in swift使用 || swift中if语句中的多个字符串
【发布时间】:2016-03-13 04:41:27
【问题描述】:

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

这是我的代码:

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

我会很感激任何帮助,甚至是朝着正确的方向轻推。

【问题讨论】:

    标签: string swift foundation command-line-tool


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      或者,如果您希望能够将 OR 条件与仅字符串值一起使用,您可以尝试以下公式

      let animal = "Fox"
      if animal == "Cat" || animal == "Dog" {
      print("Animal is a house pet.")
      } else {
      print("Animal is not a house pet.")
      }
      

      您需要记住将原始值和 == 放在要测试的每个新字符串值之前,在本例中:'animal'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        相关资源
        最近更新 更多