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

后端 未结 3 902
闹比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:13

    Typecasting is a method of telling the compiler that something is a different type than it is. It is involved in both parts of your question. You cast something by placing the new type in parentheses before the item you are casting.

    UISlider *slider = (UISlider *)sender;
    

    When the method is declared, sender has a type of id. Since you know it is supposed to be a slider, you cast it to UISlider * and store it in a variable with that type so that the compiler doesn't give you warnings when you try to use slider specific properties.

    int progressAsInt = (int)(slider.value + 0.5f);
    

    Here, slider.value is a floating point number. Since you want to store it in an integer type, you need to cast it. When a float is cast to an int, it is automatically rounded toward zero. The code wanted it rounded to the nearest integer, so it added 0.5 before casting.

提交回复
热议问题