简体   繁体   中英

Protocol Inheritance in swift

I am following this tutorial to perform TDD in swift.

About halfway down, there is a point where we need to create a protocol that inherits from UITableViewController. Code looks like the following:

import UIKit

protocol MenuTableDataSource : UITableViewDataSource {
    func setMenuItems(menuItems: [MenuItem])
}

We then create a class shortly after, that conforms to MenuTableDataSource with the following code:

import Foundation
import UIKit

class MenuTableDefaultDataSource : NSObject, MenuTableDataSource {
var menuItems: [MenuItem]?

func setMenuItems(menuItems: [MenuItem]) {
    self.menuItems = menuItems
}

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

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

However, I still get an error saying Type 'MenuTableDefaultDataSource' does not conform to protocol 'UITableViewDataSource'.

I have also tried removing the optionals in the parameters numberOfRowsInSection and cellForRowAtIndexPath but the error still persists.

Where do I seem to be going wrong? Looking at the final source code given by the author, the same error also exists, which makes me think Apple may have changed something in the syntax that we are not aware of.

Any ideas?

Thank you.

The APIs have changed a lot since that tutorial was written in September 2014.

Take a look at the API reference for UITableViewDataSource here

Namely, the main functions you are using:

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

These no longer rely on unwrapped optionals being passed in (there is no ! attached)

Swift is brand new, and the APIs went through a lot of changes between June and November-ish, so if you are reading materials online, it is always a good idea to check the official docs online. (Even the official Xcode releases and the betas can have differing APIs sometimes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM