Arkelyan
Arkelyan

Reputation: 250

swift 3 error: does not conform to protocol ‘UITableViewDataSource’

using custom swift class (not main ViewController)

Code:

import Foundation

class Myclass: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    var items: [String] = ["Item1", "Item2", "Item3"]

    override func viewDidLoad() {
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "td")
    }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "td")! as UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        print("You selected cell #\(indexPath.row)!")
    }
}

Upvotes: 3

Views: 6086

Answers (2)

Arkelyan
Arkelyan

Reputation: 250

The correct syntax for the protocol functions in Swift 3 (resolves error):

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "td")
    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Upvotes: 6

DerrickHo328
DerrickHo328

Reputation: 4886

Your method doesn't match the protocol. In swift 3 the protocol methods are different. Verify that they match.

Upvotes: 0

Related Questions