DevPrep

All topics › Objective-C

How does an Obj-C protocol differ from a Swift protocol?

Middle PRO

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:

#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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store