swift - 如何为泛型类型添加扩展?

标签 swift generics swift2

我有一个泛型类型,我想为其添加扩展,但编译器提示泛型未声明。

这是我正在尝试做的事情:

public class MyGenericType<T> {
    let abc = 123
}

extension MyGenericType<T> { // Error: Use of undeclared type 'T'

    public convenience init(value: String, defaultValue: T) {
        self.init()

        print(value)
    }

}

是否可以向 MyGenericType<T> 添加扩展名?

最佳答案

就这样做:

extension MyGenericType {
    public convenience init(value: String, defaultValue: T) {
        self.init()
        print(value)
    }
}

来自documentation :

When you extend a generic type, you do not provide a type parameter list as part of the extension’s definition. Instead, the type parameter list from the original type definition is available within the body of the extension, and the original type parameter names are used to refer to the type parameters from the original definition.

关于swift - 如何为泛型类型添加扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35815396/

相关文章:

ios - 使用可用的 : <unknown>:0: error: 'xxx' is only available on iOS 11. 0 或更新版本覆盖 open var

swift - 从多个 UICollectionVIews 内部的 UICollectionViewCell 推送一个新的 UICollectionViewController

c# - 为什么人们不将依赖属性包装在通用类中?

swift - 类型 'OSType' 不符合 Swift 2.0 中的协议(protocol) 'AnyObject'

ios - Swift Button.setText 不适用于渐变

ios - swift : Pass UITableViewCell label to new ViewController ** CRASHING **

javascript - 如何在 HTML 内的 iOS 应用程序上打开 Apple map 应用程序

ios - UITesting 验证表格单元格中是否存在复选标记

generics - 将 trait 中方法的返回类型与实现该 trait 的类型绑定(bind)

javac中java自类型递归类型参数和继承错误