gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:38:44 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com