Difference Between Delegate and DataSource (in Easy Words) ?

Let me explain what UITableViewDelegate & UITableViewDataSource are. Both UITableViewDelegate & UITableViewDataSource are protocols. What is a protocol? You can think protocol as a set of actions. 
For example UITableViewDataSource has set of actions/methods like tableView(:numberOfRowsInSection:)tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) and so on. 
What this protocol implies is that if you want to supply your custom data to the tableview, you need to conform to this protocol i.e. implement the non optional methods of the protocol(you can ignore optional methods if any).
Similarly, UITableViewDelegate has set of methods like, tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath)tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) and so on. 
UITableViewDelegate protocol implies that you need to conform to the protocol if you want to get notified when user interactions happens at tableview for example when user taps on a cell of tableview.
So now, why are you setting 
tableView.dataSource = self
tableView.delegate = self
is because you are implementing the protocols (or conforming to protocols )in your ViewController, TableViewDatasource protocol to supply your own data to the tableview, TableViewDelegate protocol to notify your ViewController class when user interacts with your tableview.

Comments

Popular posts from this blog

iOS Delegates Tutorial

iOS 11 Is Now Available: What Is New features ?

Top iOS Multiple Choice Questions And Answers For Freshers (SWIFT )