我想要做这样的事情:如何在Swift中将泛型类型约束为另一个泛型类型?
class Config<T> {
func configure(x:T)
// constraint B to be subclass of A
class func apply<A,B:A>(c:Config<A>, to:B) {
c.configure(to)
}
}
所以后来,例如,我可以申请配置到一个UILabel:
class RedViewConfig<T:UIView> : Config<T> {
func configure(x:T) {
x.backgroundColor = .redColor();
}
}
let label = UILabel()
Config.apply(RedViewConfig(), to:label)
或扩展配置类:
class RedLabelConfig<T:UILabel> : RedViewConfig<T> {
func configure(x:T) {
super.configure(x)
x.textColor = .redColor();
}
}
Config.apply(RedLabelConfig(), to:label)
我试图做到这一点,但我无法约束类。所以我尝试了协议和相关类型,但是当我重写相关类型时,我发现问题(like this)。
谢谢!所以在这种情况下,似乎我不需要两种类型。我不知道为什么我认为我需要两个。 无论如何,在某些情况下,您需要两种不同的类型。 如果我能想到一个例子,我会更新答案。 :) –