Alexis Coquard Alexis Coquard - 5 months ago 7
iOS Question

Cannot set variable to nil

I'm doing an app that shows 4 circles in different subviews and when you click on a circle it gets a little bigger then if you click on another one the last one gets back to its initial size and the new one gets bigger etc...

This is the code of the function:

func selectCircle(sender: UIButton) {
print("clicked")
if ((lastViewSelected) != nil)
{
print("lastViewSelected was not null")
if (lastViewSelected != sender.superview)
{
print("you clicked another circle")
UIView.animateWithDuration(0.5, animations: {
self.lastViewSelected!.transform = CGAffineTransformMakeScale(1, 1)
})
UIView.animateWithDuration(0.5, animations: {
sender.superview!.transform = CGAffineTransformMakeScale(1.2, 1.2)
})
}
else
{
print("you clicked the same circle")
UIView.animateWithDuration(0.5, animations: {
self.lastViewSelected!.transform = CGAffineTransformMakeScale(1, 1)
})
lastViewSelected = nil
}
}
else
{
print("lastViewSelected was so null 0 was jealous")
UIView.animateWithDuration(0.5, animations: {
sender.superview!.transform = CGAffineTransformMakeScale(1.2, 1.2)
})
}
lastViewSelected = sender.superview
}


When you clicked twice on a circle (to make it bigger then back to its size) then you could not click this one again because I check if the user click the same but the function doesn't know the state of the circle.

that's why after you click the same circle the second time I wanted to set the lastViewSelected to nil cause it went back to a zero-situation like nothing was ever clicked.

But apparently it is not happening. When I click again on a circle that was clicked and reclicked, the program is still entering the lastViewSelected != nil condition

I know I could probably deal with it using boolean but i just want to know

Why isn't the instruction
lastViewSelected = nil
working?
Does it has something to do with the animation that is running just before?

I really hope the whole explanation is clear

Answer

You're assigning it to nil and then at the end of the function you're assigning it again with lastViewSelected = sender.superview you need to return out of the function before it gets assigned again.

...

print("you clicked the same circle")
UIView.animateWithDuration(0.5, animations: {
    self.lastViewSelected!.transform = CGAffineTransformMakeScale(1, 1)
})
lastViewSelected = nil
return

...