2

This is not allowed (bad expression)

if !(let nsDictionaryObject = swiftObject as? NSDictionary)
{
    "Error could not make NSDictionary in \(self)"
    return
}

Is it possible to check for the negative of an Optional Chain expression in 1 line?

Aggressor
  • 13,323
  • 24
  • 103
  • 182

3 Answers3

10

In Swift 2.0, you can use

guard let nsDictionaryObject = swiftObject as? NSDictionary else {
    "Error could not make NSDictionary in \(self)"
    return
}

This will also bind nsDictionaryObject to the scope outside the guard statement.

Aderstedt
  • 6,301
  • 5
  • 28
  • 44
  • I will definitely try this when I upgrade to 2.0 thanks. – Aggressor Aug 14 '15 at 20:18
  • Like the `if … else` solutions above, `nsDictionaryObject` will be undefined within the `guard` scope. (`swiftObject` will still be defined.) – Aaron Brager Aug 15 '15 at 06:54
  • Yes, but having `nsDictionaryObject` defined within the `guard` doesn't make sense. What do you think it should be defined as, if the cast to `NSDictionary` fails? – Aderstedt Oct 14 '15 at 07:00
0

If you are using swift 1.2 you can do it this way:

if let nsDictionaryObject = swiftObject as? NSDictionary{} else {

    //your code

}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

In Swift 1 you could, for instance, use the else branch or check for a nil result.

var swiftObject: AnyObject = ""

if let _ = swiftObject as? NSDictionary { } else {
    println("error")
}

if swiftObject as? NSDictionary == nil {
    println("error")
}
hennes
  • 9,147
  • 4
  • 43
  • 63
  • swiftObject will not be valid in your second if, scope will be lost. – Aggressor Aug 14 '15 at 20:23
  • @Aggressor That's not correct. `swiftObject` is declared in the scope surrounding both `if` statements so it will be available inside them as well. – hennes Aug 15 '15 at 06:48
  • Yes but declaring it outside defeats the point of getting a 1 line optional chain :(. It looks like until swift 2.0 it can't be done – Aggressor Aug 15 '15 at 17:08