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?
In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type.
id is a data type of object identifiers in Objective-C, which can be use for an object of any type no matter what class does it have. id is the final super type of all objects.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
Swift Language Protocols Class-Only ProtocolsA protocol may specify that only a class can implement it through using the class keyword in its inheritance list. This keyword must appear before any other inherited protocols in this list.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With