Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if let with OR condition

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!")
}
like image 481
YogevSitton Avatar asked Jul 28 '15 07:07

YogevSitton


2 Answers

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")
    }
}
like image 186
Kametrixom Avatar answered Nov 15 '22 21:11

Kametrixom


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

like image 20
Justin Guedes Avatar answered Nov 15 '22 20:11

Justin Guedes