user3766930 user3766930 - 1 year ago 79
Swift Question

I'm checking if the object in nsdictionary is nil and I'm getting wrong response - why?

I want to store in

information if user clicked the button or not.
I have two buttons, one has +1 value, the other one -1.

When user presses one of those two buttons, I'm doing this:

if (self.defaults.objectForKey("pressedButtons") == nil){
let currentButtonId:[String:String] = [self.pressedButtons:vote]
self.defaults.setObject(currentButtonId, forKey: "pressedButtons")
} else {
var pressedButtons:[String:String] = self.defaults.objectForKey("pressedButtons") as! [String:String]
pressedButtons[self.button_id] = vote
self.defaults.setObject(pressedButtons, forKey: "pressedButtons")

in the code above
is a String value that can be either

Now, when user comes back to the panel, I'm checking if he already pressed the button or not. This is how I check it:

if (self.defaults.objectForKey("pressedButtons") != nil){

if (self.defaults.objectForKey("pressedButtons")![currentButtonId] != nil) {
print("user already pressed")
} else {
print("USER didn't press the button yet")
} else {
print("USER didn't press the button yet for sure")

the output that I always see is:

user already pressed

Since this line:


, why am I seeing the message that user pressed the button?

Answer Source

Take this object always typecasted as [String:String] while fetching

let variable = self.defaults.objectForKey("pressedButtons") as! [String:String]

Now this is a variable of type [String:String]

Now fetch your value accordingly

This doesn't know that self.defaults.objectForKey("pressedButtons") is a object with type [String:String]. So, typecast it first and then use. So self.defaults.objectForKey("pressedButtons")![currentButtonId] seems to be nil

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download