Class-only protocols, class vs AnyObject?


(Jens Persson) #1

What is the difference, if any, btw P and Q here:

protocol P : class { ... }

protocol Q : AnyObject { ... }

If no difference, which should be preferred?

(I got the impression that the class version was meant to be deprecated, but it still compiles without warnings as of Xcode 9.3)


(Thomas Krajacic) #2

See https://stackoverflow.com/questions/30176814/whats-the-difference-between-a-protocol-extended-from-anyobject-and-a-class-onl/32895975#32895975 for a subtle difference, but yes it has been stated that it will be removed. I also don’t know why it wasn’t deprecated in this release.


(Jens Persson) #3

Thanks, If the following (from @codafi’s stack overflow answer) is true:

The difference lies in the semantics of @objc declarations. With AnyObject, the expectation is that conforming classes may or may not be proper Objective-C objects, but the language treats them as such anyway (in that you lose static dispatch sometimes).

Does this mean that inheriting from AnyObject might incur a performance overhead (compared to if class had been used)?


(Slava Pestov) #4

The StackOverflow answer is out of date as of Swift 4. protocol P : class {} and protocol P : AnyObject {} parse identically and there’s no semantic difference between them. We should add a warning to deprecate the former at some point.


(Fabian) #5

The StackOverflow answer is out of date as of Swift 4. protocol P : class {} and protocol P : AnyObject {} parse identically and there’s no semantic difference between them. We should add a warning to deprecate the former at some point.

But even @jrose prefers class in his WWDC 2018 talk :stuck_out_tongue_winking_eye:


(Tino) #6

It's just fair that Swift Evolution not only breaks users code, but also creators slides ;-)


(Jordan Rose) #7

Oof, my bad. Should have had Slava review them first!


(Jon Shier) #8

Don't worry, you weren't the only presenter with imperfect Swift code. I'm pretty sure I remember a session where the presenter typed out -> Void return types. It's fairly clear that many Apple's still aren't that familiar with Swift. For some, I'm guessing WWDC slides and presentations may be the only time they write Swift at all. At least I haven't noticed any semicolons this year!


#9

Which keyword is preferred? Assumed that seems 'class' behaves incorrectly, is AnyObject better? Will class be deprecated?


(Adrian Zubarev) #10

Both are the same, class is deprecated in favor of AnyObject simply without a warning. See Slavas response above.


(Slava Pestov) #11

Both keywords behave identically. AnyObject is preferred because it is the name of a type and can appear anywhere that a type can. "class" is just special syntax in that one place in a protocol's inheritance clause, and it parses identically to "AnyObject".