Marcel Marcel - 1 year ago 49
iOS Question

Why do I have to set the dataSource and delegate to self?

I'm learning swift, and the course I'm following teaches tableViews. It I have to set the

t include
. Then, in
, I have to set

tableView.dataSource = self
tableView.delegate = self

in order for the tableView to appear and load data.

Why do I have to do this?

Answer Source

Since you said you're learning Swift just thought of writing an elobrate answer. All the above answers already explains why you need to set the delegate to self or any instance of a class. But still I thought of writing this answer just to give more insight.

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.

Actually you'll not be setting protocol conformance to self always, you can set it to instance of any class which implements the protocol.

Hope this Helps.

For more reference on protocols you can go through this: Swift 2 Tutorial Part 3: Tuples, Protocols, Delegates, and Table Views