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!")
}
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")
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With