[swift-evolution] Will Swift ever support optional methods without @objc?
Karl
razielim at gmail.com
Tue Nov 15 22:17:46 CST 2016
> On 16 Nov 2016, at 03:42, Charles Srstka <cocoadev at charlessoft.com> wrote:
>
>> On Nov 15, 2016, at 7:27 PM, Karl via swift-evolution <swift-evolution at swift.org <mailto: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
>
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161116/4abc57fe/attachment.html>
More information about the swift-evolution
mailing list