简体   繁体   English

在 Swift4 中扩展泛型类

[英]Make an extensions of generic class in Swift4

Lets assume we have a simple generic class:假设我们有一个简单的泛型类:

class Foo<T> {

}

next add to this class an extension which implements UITableViewDatasoure :接下来向此类添加一个实现UITableViewDatasoureextension

extension Foo: UITableViewDataSource {

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

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

This construction causes a compiler error with message:此构造会导致编译器错误并显示消息:

@objc is not supported within extensions of generic classes or classes that inherit from generic classes Non-'@objc' method @objc 在泛型类或从泛型类继承的类的扩展中不受支持 非'@objc' 方法

'tableView(_:numberOfRowsInSection:)' does not satisfy requirement of '@objc' protocol 'UITableViewDataSource' 'tableView(_:numberOfRowsInSection:)' 不满足 '@objc' 协议 'UITableViewDataSource' 的要求

Anyone can tell me why?谁能告诉我为什么? And how to fix that?以及如何解决这个问题?

The error message seems very clear.错误信息似乎很清楚。 This isn't supported.这不受支持。 You can't attach an @objc method to a generic class in an extension.您不能将@objc方法附加到扩展中的泛型类。 You need to define these methods in the class definition, not an extension.您需要在类定义中定义这些方法,而不是扩展名。 The "why" is "the compiler doesn't support it today." “为什么”是“编译器今天不支持它”。 (It's likely hard to support because of specializations, but the real answer is "the compiler can't do it.") (由于专业化可能很难支持,但真正的答案是“编译器做不到。”)

Currently the Xcode doesn't support attach an @objc method to a generic class in an extension, you can fix it by define the method inside the class definition, as following:目前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