dobse
dobse

Reputation: 35

Is protocol conformance in method parameters optional?

Does the Objective-C compiler not enforce that method parameters should conform to protocols, if that is how the method is declared in another protocol? I have some code that looks like:

@protocol FooProtocol<NSObject>

-(UIView <BarProtocol>*)barView;

@end

@protocol BarProtocol<NSObject>

-(BOOL)foobar;

@end

@interface FooController : NSObject<FooProtocol>

@end 

@implementation FooController {
  UIView *_view;
}

-(UIView *)barView {
  return _view;
}

@end

And the compiler doesn't complain that barView in FooController doesn't return a UIView * conforming to BarProtocol.

Upvotes: 1

Views: 58

Answers (1)

Marek R
Marek R

Reputation: 38112

In Objective C and Swift methods are invoked by name (to speed things up, only hash of selector name is compared if there is no collisions). Return type of argument types do not have impact selector name.

This means that if you are returning different type from method it will not be a problem during a run time until you will do some invalid operation on returned object (for example returned view do not implement required protocol and you have invoked this method).

Clang will detect this as a warning not an error and good practice is to fix such warnings. In fact -Wall switch during compilation is highly recommended.

Note also that protocol doesn't have to be explicitly implemented by a class. It is enough if class has all matching methods and it will work at run time.

Upvotes: 1

Related Questions