Swift’s AnyObject
You can also use AnyObject as a constraint on protocols:
protocol MyDelegate: AnyObject
. Now the implementers are known to have reference semantics, and withT: MyDelegate
you can have weak references to T, as before. You can even have weak references toany 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:
- Equality in Swift: NSObject, Subclasses, and Existentials
- Swift Generics 2: Existentials Boogaloo
- Does Swift Call the Protocol Extension or Subclass Implementation?
- Swift Protocols Wish List
- Swift Protocols