Quick equivalent to id <MyProtocol>?

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

@property (weak) id<MyDelegate> delegate;

      

How do I do this in Swift?

+3


source to share


4 answers


The protocol is a type, so you can use it as the declared type of a variable. To use weak

, you must wrap this type as optional. So you would say:

weak var delegate : MyDelegate?

      



But for this to work, MyDelegate must be a protocol @objc

or class

to ensure that the adopter is a class (and not a struct or enum, as they cannot be weak

).

+17


source


I think the exact oposite is:

weak var delegate: protocol<MyDelegate>?

      



I prefer this old objc style over swift syntax, because in swift, first is the base class and then all the accepted protocols. It can be confusing if your protocol does not have the Delegate suffix, since you don't know if DataAdoption is (for example) a superclass or a protocol.

+1


source


Use protocol as type, so:

weak var delegate:MyDelegate?

      

0


source


It's also good to know the Objective-C equivalent id<MyProtocolName>

in the Swift is method declaration protocol<MyProtocolName>

. For example:

// Objective-C
-void myMethodWithSome:(id <MyProtocolName>)param {
   // ...
}

// Swift
func myMethodWithSome(param: protocol<MyProtocolName>) {
   //...
}

      

0


source







All Articles