if let with OR condition

别等时光非礼了梦想. 提交于 2020-02-23 09:21:33

问题


Is it possible to use an "OR" condition using Swift's if let?

Something like (for a Dictionary<String, AnyObject> dictionary):

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

回答1:


This would make no sense, how would you be able to tell whether value is an Int or a String when you only have one if statement? You can however do something like this:

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


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

(Tested in Swift 2.0)

You can also do this if you need to do different things depending on the types:

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:


Unfortunately to my knowledge you cannot. You will have to use two separate if statements.

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

There are multiple ways of getting around this problem. This is just one of them. Please refer to the Apple documentation on Optional Chaining for more information on this special type of if statement. This is with using Swift 1.2



来源:https://stackoverflow.com/questions/31670295/if-let-with-or-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!