1

How do we properly test for nils?

Xcode 7.01 is throwing a new error we didn't have before.

We are receiving this error:

"Binary operator '!=' cannot be applied to operands of type '[NSObject: Anyobject]' and 'NilLiteralConvertible'"

..from this code:

// send request data to phone and handle reply or error
var didOpenParent : Bool = WKInterfaceController.openParentApplication(requestData, reply: { (reply, error) -> Void in

            // if we get a response, handle it appropriately
            if error == nil && reply != nil 
            {
                // code continues

Apple's documentation gives examples of testing for nils using "!=" as we are doing. Trying some the answers suggested here such as checking if reply.isEqual(nil) or reply.isEmpty did not work for us.

What are we missing?

Community
  • 1
  • 1
Praxiteles
  • 5,802
  • 9
  • 47
  • 78

2 Answers2

2

reply here is of type [NSObject : AnyObject], which is a non-optional dictionary type. You don't need to — and, as you've discovered, can't — check if it's nil.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • So is it accurate to say based on your answer that we can just completely delete that if statement and the code is fine? – Praxiteles Oct 21 '15 at 05:56
  • Yes, you *cannot* check something for nil which is non-optional (or more specifically, something which isn't NilLiteralConvertible and Equatable) – jtbandes Oct 21 '15 at 05:57
0

You can't check the non-optional dictionary for nil but you can make sure if the app sent u a reply dictionary by calling isEmpty

if error == nil && !reply.isEmpty
Lukas
  • 3,423
  • 2
  • 14
  • 26