Reputation: 5108
I am trying to check if a key exists in NSDictionary, and then handles the case. But why is this case being satisfied, when the value is nil?
results: NSDictionary
println(results)
prints this:
{
error = (
{
code = 402;
message = "User exists for this email";
username = "[email protected]";
}
);
}
but when I check in a if block, why is is getting inside?
if(results["results"])
{
println("why here?");
}
Here if(nil) should fail, but its not. I also tried to use, results.valueForKey("results"), results.objectForKey("results"), but all of them give exceptions.
If I use this it crashes with run-time error:
if let dict: results["results"]
Update: Just found that that the control jumps to the beginning of the function after first time is evaluated correctly, and then the run-time occurs. So why the function loops twice and then crashes?
Upvotes: 1
Views: 133
Reputation: 5108
As @Undo has mentioned in the answer above, it indeed was a problem in the later part of the function, and was throwing an exception with incorrect way the JSON data was being parsed as NSDictionary. But instead of showing where exactly the exception was occurring, xcode tries to trace back up the function and shows the exception at exit point of the function.
Fixing the JSON parsing, removed the error. Its better to write proper error handlers to avoid this kind of problems.
Upvotes: 0
Reputation: 25697
I'm trying this in a playground:
// Playground - noun: a place where people can play
import UIKit
var results = ["foo": "fooVar", "bar": "barVar"]
// ["foo": "fooVar", "bar": "barVar"]
results["foo"]
// {Some "fooVar"}
results["baz"] == nil
// true
if results["baz"]
{
"hi"
// not shown
}
else
{
"seems to be working"
//shown.
}
So there has to be something somewhere else in your program that is causing this.
Upvotes: 1
Reputation: 56635
That is not the behaviour I'm seeing. The following code prints "just what I expect"
, as expected.
let results: NSDictionary = ["foo": "bar"]
if results["baz"] {
println("why here?");
} else {
println("just what I expect");
}
There must be something else to it that isn't covered in your question.
Upvotes: 3