Tuesday, June 9, 2015

Re: Generics!

While i definitely see the potential for generics as an effective tool to prevent runtime type-mismatch errors, i feel like the loose-type checking kind of defeats the purpose...
Hopefully xcode will implement the functionality to at least flag it as a warning in their static analyzer

Best,
BK

On Jun 9, 2015, at 2:37 PM, Jens Alfke <jens@mooseyard.com> wrote:

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;

No comments:

Post a Comment