Imagine you have a protocol in Obective-C.
@protocol ABCRocket
- (void)start;
@end
What if you want to make some properties or methods optional? You can use the optional keyword.
@protocol ABCRocket
- (void)start; // Required
@optional
- (double)speed; // Optional
@end
Not all objects to implement the protocol will have the -speed method. Trying to call -speed on those objects will crash the program, so we should check if the object implements -speed first.
if ([foo respondsToSelector:@selector(speed)]) {
// Foo has the -speed method. Do something awesome!
}
It’s simple and easy.