【问题标题】:Cannot Declare Recursive Generic Type in Swift不能在 Swift 中声明递归泛型类型
【发布时间】:2017-05-29 17:12:38
【问题描述】:

我之前已经在 C# 中声明了一个递归泛型类:

  public class CommandSet<commandSetT, commandT> : ICommandSet
               where commandSetT : CommandSet<commandSetT, commandT>
               where commandT : Command
  {

  }

现在,我想在 Swift 中做同样的事情。原因是我希望 commandSetT 必须是此基类型的子类。

public class CommandSet<commandSetT, commandT : Command> : CommandSetProtocol
             where commandSetT : CommandSet<commandSetT, commandT>,
             commandT : Command
{

}

但是,编译器抱怨超类约束是递归的。

嗯,是的,因为我想确保commandSetT 是这个类的子类。

除了“好吧 Swift 不是 C#”之类的显而易见的问题之外,我真的很想听听任何知道如何执行此要求的人的意见。

【问题讨论】:

  • 我认为您应该重新考虑您的数据模型。你想解决什么问题?
  • 看起来它在路线图上Swift Generics Manifesto
  • @CodeDifferent - 能够定义泛型参数类型,使其必须从基类派生。
  • @DalijaPrasnikar - 只提到了递归协议,但我们希望它能扩展到类
  • 我希望如此。至少我看不出有什么理由不这样做。

标签: swift generics recursion


【解决方案1】:

我遇到了同样的问题,我为自己找到了一些解决方案 - 也可能对您有所帮助:

protocol A : class {
    associatedtype AType

    var aVar: AType? { get }
}

protocol B : A {
    associatedtype BType : A
}

class Test<AType> : B {
    typealias BType = Test<AType>

    var aVar: AType?
}

class Overriding : Test<String> {
    typealias BType = Overriding
}

但如果你删除它不起作用

var aVar: AType? { get }

声明,我不知道为什么;)

【讨论】:

    猜你喜欢
    • 2011-07-21
    • 1970-01-01
    • 2015-11-04
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多