Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 31 / 68

The basics of type conversion (casting)

This lesson covers type conversion in Objective-C, with the aim of converting between strings and numbers.

Converting a string to a number, or a number to a string — type conversion (casting) — is a basic programming operation. You use integerValue, stringWithFormat:, and friends.

The sample code converts the string "123" to an integer with [str integerValue] and uses it in a calculation, then converts the number 45 to a string with [NSString stringWithFormat:@"%ld", (long)n]. Note how each conversion method suits its purpose.

A common early stumble is that integerValue simply returns 0 on failure rather than reporting an error. Passing it something that is not a number is silent, so you may need to validate first.

In professional work, type conversion is a daily occurrence — using text typed into a form as a number, or turning a calculated result into text for display.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)