【发布时间】: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 - 只提到了递归协议,但我们希望它能扩展到类
-
我希望如此。至少我看不出有什么理由不这样做。