Search code examples
objective-cswiftdelegatesprotocols

Swift equivalent of id<MyProtocol>?


The question is in the title. In Objective-C, if I want to have a property (like a delegate) that HAS to adhere to a certain protocol it can be defined like so:

@property (weak) id<MyDelegate> delegate;

How can I do this in Swift?


Solution

  • A protocol is a type, so you can use it as a declared variable type. To use weak, you must wrap the type as an Optional. So you would say:

    weak var delegate : MyDelegate?
    

    But in order for this to work, MyDelegate must be an @objc or class protocol, in order to guarantee that the adopter is a class (not a struct or enum, as they cannot be weak).