Generics in Objective-C

After this year's WWDC most of us concentrated on the new features of the new operating systems (WatchOS, iOS, OS X), Swift or Xcode. However, Objective-C got some new features as well. Of course, new projects are created in Swift but there are sill a lot which were started in Objective-C and new features or bugfixing is needed. Although the new features makes better Objective-C Swift interoperability they are useful in an non-swift environment too.

The biggest improvement is the introduction of light weight generics. Foundation's built in collection types NSArray, NSSet and NSDictionary are all heterogenous. With Xcode 7 now it's possible to indicate the type! Now we can write:

NSArray <NSString*> *strings;

Which indicates that we would like to store NSString instances in the array. If we try to get one of the objects with a wrong type we get a complier warning. Although we can instantiate it with different types and of course compile it, but the warning is useful.

Of course this is handy if we are using it from a Swift environment because it will be this:

var strings : [String]

We don't have to deal with a AnyObjects in Swift this way.

Generics can be used in our own classes to:


@interface MyClass : NSObject

- (void)doSomething:(T)object;

@end

@implementation MyClass

- (void)doSomething:(id)object {
    //do something
}

@end

However these classes will become unparameterized in Swift.