How does an Obj-C protocol differ from a Swift protocol?
A protocol in Objective-C
A list of selectors a class promises to implement. @required (default) and @optional sections; the presence of an optional method is checked at runtime with respondsToSelector: before every call — otherwise unrecognized selector. Protocols can inherit from each other (@protocol Foo <NSObject>) and type variables as id<Foo>, but:
- they apply only to classes (and
id); - they cannot contain implementation — no default implementations;
- no associated types or generic constraints;
- conformance is checked formally at compile time, but at runtime you can
conformsToProtocol:and even add a protocol to a class (class_addProtocol).
#import <Foundation/Foundation.h>
@protocol Downloadable <NSObject>
- (NSURL *)downloadURL;
@optional
- (NSInteger)priority;
@end
static NSInteger priorityOf(id<Downloadable> item) {
if ([item respondsToSelector:@selector(priority)]) {
return [item priority];
}
return 0;
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep