【问题标题】:Error with Swift generics and associated typesSwift 泛型和关联类型的错误
【发布时间】:2014-09-26 07:05:06
【问题描述】:

以下 Swift 代码反复使编译器崩溃。我错过了什么?

protocol Props {
    typealias ComponentType: Component<Self>
}

class Component<PropsType: Props> {
}

class FooProps : Props {
    typealias ComponentType = FooComponent<FooProps>
}

class FooComponent<PropsType: Props> : Component<PropsType> {

}

【问题讨论】:

  • 无论代码的正确与否,编译器崩溃始终是错误
  • 是的,但这并不意味着我的代码是正确的(我怀疑它不是)——如果代码是错误的,也许正确的代码不会使编译器崩溃。如果代码是正确的,那么我需要一个解决该编译器错误的方法
  • 我不知道你的目标是什么,但导致崩溃的是“typealias ComponentType = FooComponent”这行我认为没有必要,因为如果你声明一个简单的类型别名就像 Props 中的 "typealias T = Int" 一样,你可以将它用作 FooProps 的嵌套类型。无论如何,我认为您不能使用“typealias ComponentType = Component”尝试运行此语句“var ComponentType:FooProps.ComponentType = FooComponent()”,您将看到程序运行到不定式循环中。

标签: generics swift associated-types


【解决方案1】:

关于在协议中使用泛型有一些很好的讨论。

http://schani.wordpress.com/2014/06/03/playing-with-swift/

http://schani.wordpress.com/2014/06/11/associated-types-considered-weird

第二篇文章对您的问题很有启发性。简而言之,swift 没有协议的泛型类型。希望这很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多