Minh Hoang
Minh Hoang

Reputation: 303

Why do we have to conform both UIViewController and UITableViewDataSource?

Currently, I want to have a separated class for data only. However, I cannot just declare a class like this:

class DataSource: UITableViewDataSource

It would give me a lot of error. And, I have to do this instead:

class DataSource: UIViewController, UITableViewDataSource

So, why? I come from Java background, so I don't understand why I have to implement A to implement B. I tried reading the official documents from Apple, but I could not find the answer.

Edit: here is the error:

Type 'DataSource' does not conform to protocol 'UITableViewDataSource'
Type 'DataSource' does not conform to protocol 'NSObjectProtocol'

and, XCode suggests a solution to fix it is to add "@objc " at the beginning of the override function. The error still there after the fix though.

Edit 2: I am aware that I need to implement 2 functions for the data source to work. However, it will not work without implementing UIViewController.

enter image description here

It will work after adding UIViewController!

enter image description here

Upvotes: 0

Views: 69

Answers (1)

Santosh
Santosh

Reputation: 2914

Protocol UITableViewDataSource comes from NSObjectProtocol. So you have to make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not. But many parts of UIKit expect NSObjects. And you have to implement the required methods of this protocol. Try below code:

class DataSource: NSObject, UITableViewDataSource {

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

Upvotes: 1

Related Questions