Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Rob Sanders Avatar asked May 18 '15 17:05

Rob Sanders


People also ask

What is equivalent of id 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.

What does id mean in OBJC?

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.

What is protocol in Swift 5?

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.

What is class only protocol Swift?

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.


1 Answers

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).

like image 150
matt Avatar answered Oct 06 '22 21:10

matt