34,333
edits
Changes
no edit summary
== Type Casting Objective-C Variables ==
As previously mentioned, Objective-C is a strongly typed language. In other words, once a variable has been declared as a specific data type, that type cannot be changed. It is possible, however, to make a variable behave as a different type using a concept known as ''type casting''. Suppose we have two variables declared as doubles. We need to multiply these together and display the result:
<pre>
double balance = 100.54;
double interestRate = 5.78;
double result = 0;
result = balance * interestRate;
NSLog(@"The result is %f", result);
</pre>
When executed, we will get the following output:
<pre>
The result is 581.121200
</pre>
Now, suppose that we wanted the result to the nearest whole number. We can achieve this by casting the type of both ''double'' values to type ''int'' within the arithmetic expression:
<pre>
double balance = 100.54;
double interestRate = 5.78;
double result;
result = (int) balance * (int) interestRate;
NSLog(@"The result is %f", result);
</pre>
When compiled and run, the output will now read:
<pre>
The result is 500.000000
</pre>
It is important to note that type casting only changes the way the value is read from the variable on that one occasion. It does not change the variable type or the value stored in in way. After the type cast, ''balance'' is still a ''double'' and still contains the value 100.54.