【问题标题】:if let with OR condition如果用 OR 条件让
【发布时间】:2015-07-28 07:46:37
【问题描述】:

是否可以使用 Swift 的if let 使用“OR”条件?

类似的东西(对于Dictionary<String, AnyObject> 字典):

if let value = dictionary["test"] as? String or as? Int {
       println("WIN!")
}

【问题讨论】:

  • 为什么不直接使用as? AnyObject

标签: ios swift generics


【解决方案1】:

这是没有意义的,当你只有一个 if 语句时,你怎么能判断 value 是 Int 还是 String?但是,您可以执行以下操作:

let dictionary : [String : Any] = ["test" : "hi", "hello" : 4]


if let value = dictionary["test"] where value is Int || value is String {
    print(value)
}

(在 Swift 2.0 中测试)

如果你需要根据类型做不同的事情,你也可以这样做:

if let value = dictionary["test"] {
    if let value = value as? Int {
        print("Integer!")
    } else if let value = value as? String {
        print("String!")
    } else {
        print("Something else")
    }
}

【讨论】:

    【解决方案2】:

    不幸的是,据我所知你不能。您将不得不使用两个单独的 if 语句。

    if let value = dictionary["test"] as? String {
       doMethod()
    } else if let value = dictionary["test"] as? Int {
       doMethod()
    }
    

    有多种方法可以解决这个问题。这只是其中之一。 请参阅Optional Chaining 上的 Apple 文档,了解有关这种特殊类型 if 语句的更多信息。这是使用 Swift 1.2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多