【问题标题】:swift how to determine associatedtype in sub protocolswift如何确定子协议中的关联类型
【发布时间】:2020-05-27 06:22:13
【问题描述】:

我有一个关于协议关联类型的问题。

这是代码..

protocol TestProtocol {
    associatedtype T: Equatable
}

struct Test {
    let value: TestProtocol
}

它有一个错误。

struct Test<T: TestProtocol> {
    let value: T
}

而且没关系。但我不想在结构中使用泛型。

所以我尝试了..

protocol IntTestProtocol: TestProtocol where T == Int  {

}

struct Test {
    let value: IntTestProtocol
}

但是,这段代码也有错误。

如何确定子协议中 TestProtocol 的关联类型? 有可能吗?

【问题讨论】:

  • 你要完成什么,为什么不符合协议的Test?如果你解释你想做什么,会更容易帮助你。
  • @dh0rmfpdlxm:你检查答案了吗?有效果吗?

标签: swift swift-protocols associated-types


【解决方案1】:

怎么样

protocol TestProtocol {
    associatedtype T: Equatable
}

struct TestProtocolContainer<U: Equatable>: TestProtocol {
    typealias T = U
}


struct Test {
    let value: TestProtocolContainer<Int>
}

当您使用associatedtype 声明协议时(它提供静态多态性,如果您有兴趣了解各种类型的多态性以及如何在 swift 中使用协议实现它,请阅读我的 blogpost 此处)。

您不能将该协议用作具体类型,因为编译器在编译期间无法解析 T 的类型。 (为什么在编译的时候,我说它的静态多态记住了:))

这就是为什么编译器希望您以某种方式提供它以帮助它在编译期间解析associatedtype 的类型。一种方法是提供typealias 并指定associatedtype 的实际数据类型。

示例:

struct TestProtocolContainer: TestProtocol {
    typealias T = Int
}

这很好用,但是你会希望这个通用结构来表示任何具有Equatable 类型的结构。这就是泛型发挥作用的地方。

struct TestProtocolContainer<U: Equatable>: TestProtocol {

这表示一个通用结构,它使用任何Equatable 类型并确认TestProtocol 并最终设置

typealias T = U

确保确认TestProtocol

希望对你有帮助

【讨论】:

  • @dh0rmfpdlxm:很高兴能帮上忙 :)
猜你喜欢
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 2019-08-22
相关资源
最近更新 更多