Objective-C Type Inference
I hope I got it right: This is because id
is “special”. Objects of the id
type can be sent any message you want, there is no checking done by the compiler and everything will be checked in runtime. Or, in other words, the id
type is the “dynamic typing” part of Objective-C, whereas all the other types (like NSObject
) are the “static typing” part.
This way you can choose where you want to use static typing, and where you want to use dynamic typing. It is perfectly legal to do something like this:
id str1 = @"Hello";id str2 = [str1 stringByAppendingString:@", world"];
But usually you type the strings “tightly” as NSString
s, because you get the convenience of compile-time static type check, and only resort to dynamic typing where the static one would get in the way, like in the valueForKey
situation.
Time is passed and we have better type inference now thanks to the __auto_type
available since Xcode 8. So now you can do
#define let __auto_type const#define var __auto_typelet a = @[@"pew pew"];var b = 2;b = a; //compiler warning "Incompatible pointer to integer conversion assigning to 'int' from 'NSArray *__strong const'"
and much more
In fact, I liked this so much so I made this as a pod for convenience.
pod 'SwiftyObjC'