【问题标题】:Generic parameter type 'T' cannot be inferred无法推断通用参数类型“T”
【发布时间】: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。
  • 必须有其他方法来处理。
  • 对于类类型,编译器可以通过查看其定义来确定是否符合协议。另一方面,协议类型可以是(字面上)符合该协议的任何类,因此编译器无法确定它是否是特定类的子类。

标签: ios swift generics


【解决方案1】:

我希望我能理解您的问题,即确保 UITableViewHeaderFooterView 的子类符合 CollapsableTableViewSectionHeaderProtocol 协议。

如果我的假设是正确的,你可以这样做:



//// Define a protocol
protocol CollapsableTableViewSectionHeaderProtocol {
    func sectionForUserSelectionInTableView(tableView: UITableView, atTouchLocation location:CGPoint, inView view: T) -> NSNumber?
}

class MyTableViewController: UITableViewController {
    internal func userTappedView(headerFooterView: UITableViewHeaderFooterView, atPoint location:CGPoint) {
        //// Call CollapsableTableViewSectionHeaderProtocol method
        let value = headerFooterView.sectionForUserSelectionInTableView(self.tableView, atTouchLocation: location, inView: headerFooterView)
        print(value)
    }
}

//// Implement CollapsableTableViewSectionHeaderProtocol for UITableViewHeaderFooterView via extension
extension UITableViewHeaderFooterView: CollapsableTableViewSectionHeaderProtocol {
    func sectionForUserSelectionInTableView(tableView: UITableView, atTouchLocation location:CGPoint, inView view: T) -> NSNumber? {
            //....
            return nil
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多