Thursday, July 25, 2024

Swift’s AnyObject

Jordan Rose:

You can also use AnyObject as a constraint on protocols: protocol MyDelegate: AnyObject. Now the implementers are known to have reference semantics, and with T: MyDelegate you can have weak references to T, as before. You can even have weak references to any MyDelegate, allowing swapping between delegates of different types.

What you might run into, though, is that any MyDelegate is not itself AnyObject.

[…]

Because it carries more information than just a single object reference: it also has a “witness table” pointer, the run-time representation of a protocol conformance.

[…]

But wait, Objective-C never had this problem! The id <MyDelegate> type doesn’t take up more than a single-object-reference to store! But that’s because ObjC protocols aren’t represented as tables of methods; they’re just promises that the implementing class has methods with particular names.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment