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

Greg Parker gparker at apple.com
Wed Nov 16 01:03:22 CST 2016


> On Nov 15, 2016, at 6:42 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> 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).

That's right. -conformsToProtocol: asks "does the class implementation (or some superclass thereof or category thereon) claim to conform to the protocol?" The class's method lists are not consulted.

This affects the result of -conformsToProtocol: with a protocol whose methods are all optional. Devolving to selector checks would say that all classes conform to that protocol. Honoring declared conformances as the runtime actually does gives a different answer.

This also affects the result if you add required methods to a protocol without recompiling all of the protocol's clients. Old classes will still claim to conform to the protocol, even though they might not implement the protocol's new methods.

-conformsToProtocol: is usually slower than a single -respondsToSelector: check. The latter uses the runtime's method cache while the former always walks the protocol lists of the class and all of its superclasses. But -conformsToProtocol: on a flat hierarchy with few protocols can be faster than performing multiple -respondsToSelector: checks.


-- 
Greg Parker     gparker at apple.com <mailto:gparker at apple.com>     Runtime Wrangler


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


More information about the swift-evolution mailing list