繁体   English   中英

在 Swift4 中扩展泛型类

[英]Make an extensions of generic class in Swift4

假设我们有一个简单的泛型类:

class Foo<T> {

}

接下来向此类添加一个实现UITableViewDatasoureextension

extension Foo: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //Code here
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //Code here
    }
}

此构造会导致编译器错误并显示消息:

@objc 在泛型类或从泛型类继承的类的扩展中不受支持 非'@objc' 方法

'tableView(_:numberOfRowsInSection:)' 不满足 '@objc' 协议 'UITableViewDataSource' 的要求

谁能告诉我为什么? 以及如何解决这个问题?

错误信息似乎很清楚。 这不受支持。 您不能将@objc方法附加到扩展中的泛型类。 您需要在类定义中定义这些方法,而不是扩展名。 “为什么”是“编译器今天不支持它”。 (由于专业化可能很难支持,但真正的答案是“编译器做不到。”)

目前Xcode不支持将@objc方法附加到扩展中的泛型类,您可以通过在类定义中定义方法来修复它,如下所示:

class Foo<T>: UIViewController, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //Code here ...
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //Code here ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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