Protocol Madness: Comparing Apples to Oranges from the Vantage Point of Fruit

Teaser image

Brent Simmons starts with Swift. And just as I, he struggles with value types, protocols, and generics: once a protocol references another or has a dependency on Self, you cannot use it as a type constraint or placeholder for all descending objects. You either have to use generics to expose a variant for each concrete type, or you re-write the protocol. There’s no equivalent to the way Objective-C did this: something like id<TheProtocol> just doesn’t exist. Swift is stricter. So how do you deal with that?

Continue reading …

Generics in Objective-C

Objective-C got generics! No more collection classes just for the sake of guarding against invalid elements!

I used custom collection classes a lot for the Word Counter to let the compiler help me prevent mistakes. Swift generics were a godsend for that kind of safety. Now, Objective-C can achieve similar awesomeness.

It can look like this:

@interface Wheel : NSObject
@property (nonatomic, strong) UIColor *color;
@end

@interface Vehicle : NSObject
@property (nonatomic, copy) NSArray<Wheel *> *wheels;
@end

Now the compiler will warn (!) you if you misuse it:

Vehicle *car = [[Vehicle alloc] init];
[car.wheels addObject:@"NSString is of the wrong type"];

Great news, since if you didn’t spend a lot of time creating custom collection types yourself, now at last can you ensure array element type consistency. Makes your code cleaner and more reliable.