【问题标题】:Protocol Inheritance in swiftswift中的协议继承
【发布时间】:2015-01-27 01:21:50
【问题描述】:

我正在关注this 教程以快速执行 TDD。

大约到了一半,有一点我们需要创建一个继承自 UITableViewController 的协议。代码如下所示:

import UIKit

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

然后我们很快创建了一个类,它符合 MenuTableDataSource 的代码,代码如下:

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;
}
}

但是,我仍然收到一条错误消息,提示类型“MenuTableDefaultDataSource”不符合协议“UITableViewDataSource”。

我也尝试删除参数 numberOfRowsInSection 和 cellForRowAtIndexPath 中的选项,但错误仍然存​​在。

我似乎哪里出错了?查看作者给出的最终源代码,同样的错误也存在,这让我觉得Apple可能在语法上改变了一些我们不知道的东西。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: ios uitableview swift protocols


    【解决方案1】:

    自 2014 年 9 月编写该教程以来,API 发生了很大变化。

    查看UITableViewDataSource here 的 API 参考

    即你正在使用的主要功能:

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

    这些不再依赖于传入的未包装选项(没有附加!

    Swift 是全新的,API 在 6 月和 11 月之间经历了很多变化,所以如果您在线阅读资料,最好在线查看官方文档。 (即使是官方 Xcode 版本和 beta 有时也可能有不同的 API)

    【讨论】:

    • 是的,正如 OP 中所述,我已尝试删除 !在参数中,问题仍然存在。有趣的是,当我开始输入“tableView”时,代码完成建议仅显示 UITableViewDataSource 中的一些方法,例如 titleForFooterInSection 和 titleForHeaderInSection。但是,我正在寻找的方法,即 cellForRowAtIndexPath 和 numberOfRowsInSection 没有通过代码完成显示(即使这些方法的当前实现首先被注释掉)。我很困惑为什么会发生这种情况?
    • 我只是将this 放入情节提要中,编译器没有抱怨任何事情(Xcode 6.2 (6C107a))。 (这不是你返回UITableViewCells的方式,但你需要返回一些东西)
    • 好的,在查看您的代码后,我删除了方法签名和 cellForRowAtIndexPath 中的所有选项,我像您一样返回 UITableViewCell() 而不是 nil。这似乎解决了问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多