What does a type name in parentheses before a variable mean?

后端 未结 3 908
闹比i
闹比i 2021-01-24 13:29

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

3条回答
  •  旧巷少年郎
    2021-01-24 14:05

    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, orUISlider *`, 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 ints, so instead you say "Please turn this float into an int for me", by putting the (int) in front.

提交回复
热议问题