I am important p A prerequisite is understanding the protocols for the first delegates. I recommend reviewing this short tutorial first, and then What is a protocol? . In addition, you MUST know the difference between a class and a protocol, so see Objective-C: class versus protocol and What is the meaning of protocols? .
protocol: is ONLY a project of the functions to be implemented. Any class that adopts this plan will have to implement these functions. (DO NOT confuse function implementation with function call)
delegate: 1 also allows you to do what the delegat- ing class does without inheritance , for example
For example, you have a viewController and you want to upload images, or you want to get the customer distance to the store, so instead of doing it all yourself, you just have a middle object that does it for you. This object is known as a delegate object. Usually you do something like this:
class ViewController : UIViewController , DownloaderDelegate{
very similar to what you do to match tableViewDelegate
class ViewController : UIViewController , UITableViewDelegate{
your self can now also do tableView related things.
delegate: 2 But this object (delegate) is a simple vanilla object (id or Any). This is stupid! You have to say this: "Hey, you have to work to have the specific functionality that you need in order to comply with the protocol that we have defined for you (we are not going to extend Any or id, as it would be stupid, (instead) we made a very explicit limited protocol "
in Objective-C this is pure vanilla id so what do you do
@property (weak) id<DownloaderProtocol>delegate;
in Swift * this is a little easier to do:
weak var delegate:DownloaderProtocol?
The protocol comes to the rescue ... the delegate implements (rather than uses) the function to fit the needs of your delegating class.
*: In Swift, you donβt have an id , but you donβt need its Any equivalent, because in Swift the protocols are also of the first-class citizens type.