Fogia Fogia - 1 month ago 15
Swift Question

Swift AnyObject as Dictionary get element that doesn't exist is not nil

I'm confronted to a problem with cast in Swift

Here the code :

init(response: NSHTTPURLResponse, representation: AnyObject)
{
super.init(entity:NSEntityDescription.entityForName("File", inManagedObjectContext: NSManagedObjectContext.currentContext())!, insertIntoManagedObjectContext:NSManagedObjectContext.currentContext());

var result : [String:AnyObject] = representation as! [String : AnyObject];
if representation["result"] != nil {
print("result = \(representation["result"])")
result = representation["result"] as! [String : AnyObject]
}
}


In some cases i expect that representation["result"] equal nil, in that cases when i print representation["result"] the debuger give me nil but I still pass the condition and display "result = nil" in the log and when it executes next line it crashes
fatal error: unexpectedly found nil while unwrapping an Optional value
Which is normal because I try to unwrap a nil value!

But I did found that if I do:

var result : [String:AnyObject] = representation as! [String : AnyObject];
if result["result"] != nil {
print("result = \(result["result"])")
result = representation["result"] as! [String : AnyObject]
}


It works pretty well

I know, I know some of you will say: you found a solution why post on stackoverflow-
I did because i want to understand why the first solution doesn't work, and because my error is certainly not specific to this context.

Answer

Because you have to cast representation["result"] to a dictionary before you check it, so if you type representation["result"] as! [String : AnyObject] it should work properly.