[swift-evolution] Will Swift ever support optional methods without @objc?

Charles Srstka cocoadev at charlessoft.com
Tue Nov 15 20:42:05 CST 2016


> On Nov 15, 2016, at 7:27 PM, Karl via swift-evolution <swift-evolution at swift.org> 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161115/99d2b24b/attachment.html>


More information about the swift-evolution mailing list