我有一个泛型类型,我想为其添加扩展,但编译器提示泛型未声明。
这是我正在尝试做的事情:
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/