Objective-C Generics
A small detour
In Xcode 7 Clang learned a new trick: Objective-C generics. Now that I've started using this feature in our legacy code I can't live without it. Even without Swift interop consequences I would still use it.
The What
Objective-C can now declare that an NSArray
is an NSArray<NSString *>
. This helps on the Objective-C side by giving you a warning if you try to take UIImage *
out of the array. But it really shines when interacting with system frameworks because UIView.subviews
now shows up in Swift as Array<UIView>
instead of Array<AnyObject>
. It also helps when bridging to your own legacy Objective-C code because the Swift collections all automatically carry this information.
__kindof
says this thing must be X or a more-derived class. Why is this necessary? The docs don't call this out but I suspect its because adding generics to Objective-C introduces a massive conundrum: If UIView.subviews
is now NSArray<UIView *>
then a whole lot of code is now invalid according to the compiler's type checker: [view.subviews[0] setImage:nil]
is bogus because UIView
doesn't have an image
property. We've been spoiled by the fact that the Objective-C compiler will let you send any visible message selector to id
... only now the subviews array doesn't return id
, it returns UIView *
. Oops.
__kindof
solves that problem by saying the subviews array isn't explicitly an array of UIView *
but an array of UIView *
subclasses. Then the compiler will let you send any selectors that could apply to UIView *
or all its subclasses, or assign an element from that array to a UIImageView *
, but it will still complain if you attempt to do this: NSNumber *n = view.subviews[0]
.
With Limits
There's a major caveat: Only the built-in collection types bridge from Swift using this new mechanism; your own custom methods and generic classes do not. (Maybe someday Objective-C can gain full generics support but I suspect therein lies the path of pain and sadness.)
Meta
I haven't been blogging because I have been super busy the past few months. The good news is I've been busy working in really awesome stuff that I'll be writing about shortly. If you're interested in CoreImage GLSL shaders, UITouchTypeStylus
, the iOS touch event handling system, Split View Multitasking, or even using Xcode to build programs for Arduino embedded systems then you'll be very pleased.
This blog represents my own personal opinion and is not endorsed by my employer.