DevPrep

All topics › Objective-C

The id type

Middle PRO

Essence

id is a pointer to any Objective-C object (technically struct objc_object *; the asterisk is already part of the type). It is the "dynamic type": with an id variable the compiler allows sending any selector known from at least one imported header, and requires no cast when assigning to or from any other object type. nil is the zero value of id.

#import <Foundation/Foundation.h>

static void demo(NSArray *items) {
    id first = items.firstObject;         // type unknown until runtime
    if ([first isKindOfClass:[NSString class]]) {
        NSString *s = first;              // implicit conversion, no cast
        NSLog(@"%lu", (unsigned long)s.length);
    }
    id<NSCopying> key = @"k";             // id constrained by a protocol
    NSDictionary *d = @{key: @1};
    NSLog(@"%@", d);
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store