我对协议关联类型有疑问。
这里是代码。.
protocol TestProtocol {
associatedtype T: Equatable
}
struct Test {
let value: TestProtocol
}
有错误。
struct Test<T: TestProtocol> {
let value: T
}
而且还可以。但我不想在struct中使用泛型。
所以我尝试了..
protocol IntTestProtocol: TestProtocol where T == Int {
}
struct Test {
let value: IntTestProtocol
}
但是,此代码也有错误。
如何确定子协议中的TestProtocol的关联类型?有可能吗?
怎么样
protocol TestProtocol {
associatedtype T: Equatable
}
struct TestProtocolContainer<U: Equatable>: TestProtocol {
typealias T = U
}
struct Test {
let value: TestProtocolContainer<Int>
}
[当您声明带有associatedtype
的协议(它提供静态多态性时,如果您有兴趣了解各种类型的多态性以及如何快速通过协议实现它,请在此处阅读我的blogpost)。
您不能将该协议用作具体类型,因为编译器在编译期间无法解析T
的类型。 (为什么编译,我说过它的静态多态性请记住:)))
因此,编译器希望您提供某种方式以帮助其在编译期间解析associatedtype
的类型。一种方法是提供typealias
并指定associatedtype
的实际数据类型。
示例:
struct TestProtocolContainer: TestProtocol { typealias T = Int }
这很好用,但是接下来,您需要使此泛型结构表示任何具有
Equatable
类型的结构。那就是泛型出现的地方。
struct TestProtocolContainer<U: Equatable>: TestProtocol {
[这表示使用任何
Equatable
类型并确认TestProtocol
并最终设置的通用结构
typealias T = U
确保确认
TestProtocol
希望这会有所帮助