iOS Dev Nugget 278 Type Inference for Objective-C


Need to run a code review on your codebase? Hire me

Maybe it's an existing project, or for some other reason you are still using Objective-C, here's a nugget for you:

__auto_type i = @123;
NSLog(@"class: %@", NSStringFromClass([i class]));

const __auto_type j = @123;
j = @1;

That last line will compile with an error:

Cannot assign to variable 'j' with const-qualified type 'NSNumber *__strong const'

Typing _auto_type and const __auto_type looks a little unwieldy, so we can define a few macros:

#define let const __auto_type
#define var __auto_type

and use them instead:

var i = @123;
NSLog(@"class: %@", NSStringFromClass([i class]));

let j = @123;
j = @1; //Compilation error

(Probably more useful to store the macros in a new header file and #import them)

I picked up this tip from @_nb

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues