> On 16 Nov 2016, at 03:42, Charles Srstka <[email protected]> wrote:
>
>> On Nov 15, 2016, at 7:27 PM, Karl via swift-evolution
>> <[email protected] <mailto:[email protected]>> wrote:
>>
>> In Objective-C, asking whether or not an object conforms to a protocol just
>> cascades in to a bunch of calls to “respondsToSelector”, so it’s also very
>> painful.
>
> This isn’t true; Objective-C stores a list of protocols that a class conforms
> to, so -respondsToSelector: does not need to be called when checking protocol
> conformance (also: simply adopting a protocol’s methods will not cause a
> class to conform to the protocol).
>
> You can test this yourself:
>
> #import <Foundation/Foundation.h>
>
> @protocol P
>
> - (void)foo;
>
> @end
>
> @interface C: NSObject<P>
>
> - (void)foo;
>
> @end
>
> @implementation C
>
> - (void)foo {
> NSLog(@"foo");
> }
>
> - (BOOL)respondsToSelector:(SEL)selector {
> NSLog(@"respondsToSelector: called");
>
> return [super respondsToSelector:selector];
> }
>
> @end
>
> int main(int argc, char *argv[]) {
> @autoreleasepool {
> C *c = [C new];
>
> NSLog(@"C is P: %@", [c conformsToProtocol:@protocol(P)] ?
> @"YES" : @"NO");
> }
> }
>
> The output is only:
>
> C is P: YES
>
> The log we put in -respondsToSelector: never gets printed.
>
> Charles
>
Huh. I’ve been using Objective-C for maybe 15 years and I’ve always avoided
“conformsToProtocol” because I didn’t think it gave a strong contract like
that. You learn something new every day :)
- Karl
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution