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