I am having a bit of trouble understanding this piece of code. It is from a book I am reading but I feel like the guy is just telling me to type stuff without explaining it in m
Basically, the computer (compiler, actually, but we can pretend for simplicity's sake) only knows what kind of thing you are referring to because of its "type". The type could be an int, or
UISlider *`, or any number of other things. It is a classification for a variable.
At the top, you can see that sender
is of type id
, which means the computer has no idea what kind of object it is.
When this method is called, you receive an object which is called sender
. But even though you know that sender is a UISlider*
, you can't call UISlider methods on it, because the computer doesn't know that.
When you say UISlider *slider = (UISlider *)sender;
, you are saying "Hey computer, I'm telling you that sender is a UISlider *
, and I'm going to refer to it as slider
from now on. That is what typecasting is.
The same goes for int progressAsInt = (int)(slider.value + 0.5f);
(slider.value + 0.5f)
is actually a float
, which is alike a number with decimals. You can't just assign a float to a variable meant for int
s, so instead you say "Please turn this float into an int for me", by putting the (int)
in front.