【发布时间】:2016-01-31 22:20:40
【问题描述】:
我从这个代码中得到一个错误'无法推断通用参数类型'T'。
public func userTappedView(headerFooterView: CollapsableTableViewSectionHeaderProtocol, atPoint location:CGPoint) {
if let tableView = self.collapsableTableView() {
//Error here
let value = sectionForUserSelectionInTableView(tableView, atTouchLocation: location, inView: headerFooterView)
...
}
...
}
func sectionForUserSelectionInTableView<T: UITableViewHeaderFooterView where T: CollapsableTableViewSectionHeaderProtocol>(tableView: UITableView, atTouchLocation location:CGPoint, inView view: T) -> NSNumber? {
...
}
【问题讨论】:
-
您将 CollapsableTableViewSectionHeaderProtocol 传递给需要 UITableViewHeaderFooterView 的方法。任何类都可以实现该协议;因此,编译器无法推断您传递的对象是 UITableViewHeaderFooterView 子类。
-
如何保证 UITableViewHeaderFooterView 的子类符合 CollapsableTableViewSectionHeaderProtocol 协议?
-
如果你知道它将是一个 UITableViewHeaderFooterView,你可以强制转换它,或者将 userTappedView 的定义更改为需要一个 UITableViewHeaderFooterView。
-
必须有其他方法来处理。
-
对于类类型,编译器可以通过查看其定义来确定是否符合协议。另一方面,协议类型可以是(字面上)符合该协议的任何类,因此编译器无法确定它是否是特定类的子类。