【问题标题】:If let - Multiple conditions如果让 - 多个条件
【发布时间】:2016-03-23 07:45:08
【问题描述】:

我可以在 IF 中使用 let obj = something 的多个条件

if let u = custom["u"] as? String || let url = custom["URL"] as? String
{
// Do something here
}

【问题讨论】:

    标签: ios swift swift2 optional


    【解决方案1】:

    您可以添加多个条件,但前提是您使用 AND 条件。

    如果您使用OR,您不知道您的哪个值设置正确,因此无法正确访问变量。

    通过AND 测试,您可以确定这两个变量都已正确创建,因此您可以肯定地知道它们的类型。

    您必须编写用逗号分隔的测试:

    if let u = custom["u"], 
       let url = custom["URL"] {
        // Do something here
    }
    

    此外,您可以在 if let 块之后直接添加一些条件,使用 where 关键字:

    if let u = custom["u"] where u == "testValue", 
       let url = custom["URL"] {
        // Do something here
    }
    

    【讨论】:

      【解决方案2】:

      我假设您的收藏类型是Dictionary

      如果你真的想用OR

      if(custom.keys.contains("u") || custom.keys.contains["URL"]) { }
      

      但是正如其他人已经写的那样,这并没有真正的意义,因为如果您需要这些键的值,您仍然必须编写两个单独的 if 语句。

      if let u = custom["u"] {
          print("Value for u: \(u!)");
      }
      
      if let url = custom["URL"] {
          print("Value for URL: \(url!)");
      }
      

      【讨论】:

        【解决方案3】:

        1) 它对 OR 没有意义 2) 用 AND 代替

        if let u = custom["u"] as? String,
        let url = custom["URL"] as? String {
        // Do something here
        }
        

        【讨论】:

          【解决方案4】:

          我同意 user3441734。你为什么要这样做?

          if let u = custom["u"] as? String { 
              if let url = custom["URL"] as? 
              // Do something here
              }
          }
          

          我会这样做。只有当上述条件为真或:

           if let u = custom["u"] as? String { 
               // Call same method 
           }
           if let url = custom["URL"] as? 
               // Call same method 
           }
          

          这样会检查并执行这两个。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多