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

Type-agnostic general functions (the id type)

This lesson covers writing type-agnostic functions with the id type in Objective-C, with the aim of producing flexible code that handles several types.

The id type is Objective-C's special type meaning "any object at all". Its dynamically typed character is handy when the same logic should serve numbers and strings alike.

In the sample code, the definition id larger(id a, id b) compares both a number object such as @3 and a string object such as @"apple" through the same function. The point is that compare: works on both types.

A common early stumble is that using id turns off compile-time type checking. Nothing guarantees the object really has a compare: method, and passing the wrong type is a run-time error.

In professional work, the convenience of not writing near-identical methods per type has to be weighed against that loss of type safety.

๐Ÿ“– 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)