如果让OR条件

Yog*_*ton 7 generics ios swift

是否可以使用Swift的"OR"条件if let

像(对于Dictionary<String, AnyObject>字典):

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

Kam*_*xom 12

这没有任何意义,当你只有一个if语句时,你怎么能告诉值是Int还是String?但是你可以这样做:

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


if let value = dictionary["test"] where value is Int || value is String {
    print(value)
}
Run Code Online (Sandbox Code Playgroud)

(在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")
    }
}
Run Code Online (Sandbox Code Playgroud)