【问题标题】:How to add an extension to generic type?如何为泛型类型添加扩展?
【发布时间】:2016-03-05 14:39:28
【问题描述】:

我有一个泛型类型,我想为其添加扩展,但编译器抱怨没有声明泛型。

这是我想要做的:

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&lt;T&gt;添加扩展名?

【问题讨论】:

    标签: swift generics swift2


    【解决方案1】:

    只要做:

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

    来自documentation:

    当您扩展泛型类型时,您不提供类型参数列表作为扩展定义的一部分。相反,original 类型定义中的类型参数列表在扩展的主体中可用,并且原始类型参数名称用于引用原始定义中的类型参数。

    【讨论】:

    • 但是如何使convenience init 中的第二个参数成为泛型类型?
    • 您只需使用T。请参阅文档中引用的回复补充内容。
    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2011-08-28
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多