The new generics support in Objective-C (starting in Xcode 7) is interesting, 
although there’s no real documentation that I can find, just a one-paragraph 
mention in the Foundation release notes. But if you look at NSArray.h or 
NSDictionary.h in the OS X 10.11 or iOS 9 SDK, you can see lots of examples of 
their use.

(There’s also a somewhat related new keyword __kindof, also described in the 
release notes, that gives you un-typechecked down-casting. So an RHS of type 
“__kindof NSView*” can be assigned to a LHS of type MyViewClass* without a 
type-cast. Nice.)

I’m guessing that the primary reason generics were added was to make the Cocoa 
APIs more Swift-friendly, so the Swift APIs don’t just use [AnyObject] and 
[AnyObject:AnyValue] everywhere.

They’ll be useful for Obj-C programming too though, of course. I tried 
parameterizing the NSArray and NSDictionary types that appear in some APIs in 
my code, and everything rebuilt without errors. Which is nice in that it didn’t 
break everything and require massive replacing; but on the other hand it shows 
that generics are pretty loosely type-checked. It seems that you can freely 
assign between, say, NSArray<NSString*>* and a regular NSArray* without any 
warnings or errors. In fact you can use the generic form in a method’s 
declaration in a class interface, but leave the old form in the 
@implementation, without any warnings.

For backward compatibility in my APIs I’m doing stuff like this:
#if __has_feature(objc_generics)
typedef NSDictionary<NSString*, id> CBLJSONDict;
#else
typedef NSDictionary CBLJSONDict;
#endif
and then replacing “NSDictionary” with “CBLJSONDict” where appropriate.

—Jens
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/objc-language/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to