Generics?

Any documentation on this new Xcode 7 feature? The Xcode release notes say:


Generics. Specify type information for collections, simplifying the code you write.


Without any more detail.

Accepted Reply

Check out "Objective-C Language Features" in the Xcode 7 beta Release Notes.


Specifically:


Lightweight generics allow you to specify type information for collection classes like NSArray, NSSet, and NSDictionary. The type information improves Swift access when you bridge from Objective-C and simplifies the code you have to write. (6294649)

For example:

NSArray<UIImage *> *images; NSDictionary<NSString *, NSURL *> *resourcesByName;


Replies

Check out "Objective-C Language Features" in the Xcode 7 beta Release Notes.


Specifically:


Lightweight generics allow you to specify type information for collection classes like NSArray, NSSet, and NSDictionary. The type information improves Swift access when you bridge from Objective-C and simplifies the code you have to write. (6294649)

For example:

NSArray<UIImage *> *images; NSDictionary<NSString *, NSURL *> *resourcesByName;


There is some information hereon how collections typed using generics are imported into Swift (look under Lightweight Generics).


Does "Lightweight" maybe mean I can't create my own generic classes; just use NSArray<T>, NSSet<T>, NSDictionary<T>?

If you dig in to the Xcode-beta bundle and find the framework headers, here's how NSArray is now declared:


@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>


That "<__covariant ObjectType>" bit sure looks to me like a user-accessible generic syntax. ("Covariant" and its opposite, "contravariant", have to do with which direction the types should be considered compatible in; for instance, should you be able to pass an NSArray<NSString *> where an NSArray<NSObject *> is expected? Or vice versa? Or neither one?)

Thanks!


I also managed to dig up information in the Swift - ObjC bridging book. Cool stuff. Hopefully Apple has liberally sprinkled their API with generics to reduce casting in Swift.

I've written a blog post about them and also about how implement them on any class. See here http://drekka.ghost.io/objective-c-generics/