是否有可能使用「OR」條件使用斯威夫特的if let
?如果與或條件讓
喜歡的東西(一個Dictionary<String, AnyObject>
字典):
if let value = dictionary["test"] as? String or as? Int {
println("WIN!")
}
是否有可能使用「OR」條件使用斯威夫特的if let
?如果與或條件讓
喜歡的東西(一個Dictionary<String, AnyObject>
字典):
if let value = dictionary["test"] as? String or as? Int {
println("WIN!")
}
這將是沒有意義的,當只有一個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)
}
(在雨燕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")
}
}
不幸的是,據我所知,你不能。你將不得不使用兩個單獨的if語句。
if let value = dictionary["test"] as? String {
doMethod()
} else if let value = dictionary["test"] as? Int {
doMethod()
}
解決此問題有多種方法。這只是其中之一。 有關此特殊類型if語句的更多信息,請參閱Optional Chaining上的Apple文檔。這是與使用Swift 1.2
爲什麼不只是使用'as? AnyObject' – sbarow