快速确定子协议中的关联类型

问题描述 投票:0回答:1

我对协议关联类型有疑问。

这里是代码。.

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的关联类型?有可能吗?

swift swift-protocols associated-types
1个回答
0
投票

怎么样

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

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.