swift - 无法在 Swift 中声明递归泛型类型

标签 swift generics recursion

我之前在 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
{

}

但是,编译器提示父类(super class)约束是递归的。

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

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

最佳答案

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

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 }

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

关于swift - 无法在 Swift 中声明递归泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247551/

相关文章:

algorithm - 最大化给定股票报价的利润

c++ - 使用for循环递归地乘以数组中的元素

objective-c - 如何在 Swift 中使用 Objective C 的类类别?

ios - 为什么 float 值在 playground 中四舍五入而不是在 Swift 的项目中?

ios - 无法识别的选择器发送到实例 0x7fe098c09830

R:在全局环境中从包 ‘split’ 为 ‘base’ 创建通用函数

json - Swift:过滤 TableView 中的结果,因此它不会从 JSON 返回重复项

java - wtf.is.going.on 中的抽象方法foo(E) 无法直接访问super.foo(e) 用ANT 编译

java - Spring 3.2 Autowire 泛型类型

json - 将递归 Json 映射到类 Flutter