通用参数类型' T'无法推断

时间:2016-01-31 22:20:41

标签: ios swift generics

我从此代码'通用参数类型' 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? {
    ...
}

1 个答案:

答案 0 :(得分:0)

我希望我理解您的问题,即确保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
    }
}